package org.fxc.nio.server;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator; public class NIOServer {
static int BLOCK = 500*1024; /**
* 处理客户端的内部类,专门负责处理与用户的交互
*/
public class HandleClient {
protected FileChannel channel;
protected ByteBuffer buffer;
String filePath; /**
* 构造函数,文件的管道初始化
* @param filePath
* @throws IOException
*/
public HandleClient(String filePath) throws IOException { //文件的管道
this.channel = new FileInputStream(filePath).getChannel(); //建立缓存
this.buffer = ByteBuffer.allocate(BLOCK);
this.filePath = filePath;
} /**
* 读取文件管道中数据到缓存中
* @return
*/
public ByteBuffer readBlock() {
try { //清除缓冲区的内容,posistion设置为0,limit设置为缓冲的容量大小capacity
buffer.clear(); //读取
int count = channel.read(buffer); //将缓存的中的posistion设置为0,将缓存中的limit设置在原始posistion位置上
buffer.flip();
if (count <= 0)
return null;
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
} /**
* 关闭服务端的文件管道
*/
public void close() {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} protected Selector selector;
protected String filename = "d:\\film\\hadoop-1.1.2.tar.gz"; // a big file
protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);
protected CharsetDecoder decoder; //构造服务端口,服务管道等等
public NIOServer(int port) throws IOException {
selector = this.getSelector(port);
Charset charset = Charset.forName("GB2312");
decoder = charset.newDecoder();
} // 获取Selector
//构造服务端口,服务管道等等
protected Selector getSelector(int port) throws IOException {
ServerSocketChannel server = ServerSocketChannel.open();
Selector sel = Selector.open();
server.socket().bind(new InetSocketAddress(port));
server.configureBlocking(false); //刚开始就注册链接事件
server.register(sel, SelectionKey.OP_ACCEPT);
return sel;
} // 服务启动的开始入口
public void listen() {
try {
for (;;) {
//?
selector.select();
Iterator<SelectionKey> iter = selector.selectedKeys()
.iterator();
while (iter.hasNext()) {//首先是最先感兴趣的连接事件
SelectionKey key = iter.next();
//?
iter.remove(); //处理事件
handleKey(key);
}
}
} catch (IOException e) {
e.printStackTrace();
}
} // 处理事件
protected void handleKey(SelectionKey key) throws IOException {
if (key.isAcceptable()) { // 接收请求 //允许网络连接事件
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel channel = server.accept();
channel.configureBlocking(false); //网络管道准备处理读事件
channel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) { // 读信息
SocketChannel channel = (SocketChannel) key.channel(); //从客户端读过来的数据块
int count = channel.read(clientBuffer);
if (count > 0) { //读取过来的缓存进行有效分割,posistion设置为0,保证从缓存的有效位置开始读取,limit设置为原先的posistion上
//这样一来从posistion~limit这段缓存数据是有效,可利用的
clientBuffer.flip(); //对客户端缓存块进行编码
CharBuffer charBuffer = decoder.decode(clientBuffer);
System.out.println("Client >>download>>" + charBuffer.toString()); //对网络管道注册写事件
SelectionKey wKey = channel.register(selector,
SelectionKey.OP_WRITE); //将网络管道附着上一个处理类HandleClient,用于处理客户端事件的类
wKey.attach(new HandleClient(charBuffer.toString()));
} else{
//如客户端没有可读事件,关闭管道
channel.close();
} clientBuffer.clear();
} else if (key.isWritable()) { // 写事件
SocketChannel channel = (SocketChannel) key.channel(); //从管道中将附着处理类对象HandleClient取出来
HandleClient handle = (HandleClient) key.attachment(); //读取文件管道,返回数据缓存
ByteBuffer block = handle.readBlock();
if (block != null){
//System.out.println("---"+new String(block.array())); //写给客户端
channel.write(block);
}else {
handle.close();
channel.close();
}
}
} public static void main(String[] args) {
int port = 12345;
try {
NIOServer server = new NIOServer(port);
System.out.println("Listernint on " + port);
while (true) {
server.listen();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Nio Server的更多相关文章

  1. Netty3 源代码分析 - NIO server绑定过程分析

    Netty3 源代码分析 - NIO server绑定过程分析      一个框架封装的越好,越利于我们高速的coding.可是却掩盖了非常多的细节和原理.可是源代码可以揭示一切. 服务器端代码在指定 ...

  2. 一段关于java NIO server端接受客户端socket连接;演示了关于channel,selector等组件的整合使用

    public class ReactorDemo { public static void main(String[] args) throws IOException { ServerSocketC ...

  3. Java nio Server端示例

    public class ServerNio { public static void main(String[] args) throws IOException, InterruptedExcep ...

  4. NIO vs. BIO

    性能测试 BIO -- Blocking IO 即阻塞式IO NIO -- Non-Blocking IO, 即非阻塞式IO或异步IO 性能 -- 所谓的性能是指服务器响应客户端的能力,对于服务器我们 ...

  5. 从Jetty、Tomcat和Mina中提炼NIO构架网络服务器的经典模式(三)

    转载 http://blog.csdn.net/cutesource/article/details/6192163 最后我们再看看NIO方面最著名的框架Mina,抛开Mina有关session和处理 ...

  6. java NIO的多路复用及reactor模式【转载】

    关于java的NIO,以下博客总结的比较详细,适合初学者学习(http://ifeve.com/java-nio-all/) 下面的文字转载自:http://www.blogjava.net/hell ...

  7. java nio的一个严重BUG(转)

    这个BUG会在linux上导致cpu 100%,使得nio server/client不可用,具体的详情可以看这里http://bugs.sun.com/bugdatabase/view_bug.do ...

  8. Java NIO的多路复用及reactor

    (from:http://developer.51cto.com/art/201112/306489.htm) 以下描述,为了说明问题,就提提历史(类似的东西,网上一搜一大把,但是希望你能在这里止步, ...

  9. tomcat bio nio apr 模式性能测试

    转自:tomcat bio nio apr 模式性能测试与个人看法 11.11活动当天,服务器负载过大,导致部分页面出现了不可访问的状态.那后来主管就要求调优了,下面是tomcat bio.nio.a ...

随机推荐

  1. Mysql中Key与Index的区别

    mysql的key和index多少有点令人迷惑,这实际上考察对数据库体系结构的了解的. 1 key 是数据库的物理结构,它包含两层意义,一是约束(偏重于约束和规范数据库的结构完整性),二是索引(辅助查 ...

  2. 关于写的Java书籍进展

    大家好,去年说要写本Java书,近期就快出版了.眼下已经開始打印样书了,最快于本月中旬左右就能够在互动网www.china-pub.com上看到消息,其它各个站点何时会发售要看详细进货情况. 去年我预 ...

  3. C# webservice开发

      一.Webservice简介Web Service也叫XML Web Service. Web Service是一种可以接收从Internet或者Intranet上的其它系统中传递过来的请求,轻量 ...

  4. 文件和文件夹权限-Win7公共盘中出现大量临时文件

    公司中有一个文件服务器,给不同部门和员工设置了不同的权限,最近有员工(没有修改权限,有读取及执行,读取,写入)反映在公共盘上修改文件的时候会产生大量的临时文件,添加上修改权限之后就可以了,然后被同事问 ...

  5. Dell 2950服务器CPU-E1422错误解决方法

    .造成原因:CPU松动或者是硅胶损耗 .解决方法: .断掉电源,将其后盖打开(在手没有静电的情况下操作) .拔掉周围的排热扇 .按住关卡,将其CPU卸下:并使用清洁剂清理,再次给CPU上涂上硅胶(均匀 ...

  6. Oracle的用户管理,授权及备份

    一.用户进行授权的操作 创建用户:刚刚创建的用户并没有任何权限 CREATE USER 用户名 indentife BY 密码 授权:  GRANT 权限1,权限2... TO 用户权限有:CREAT ...

  7. Spring 4.0 中的 WebSocket 架构

    两年前,客户端与服务器端的全双工双向通信作为一个很重要的功能被纳入到WebSocket RFC 6455协议中.在HTML5中,WebSocket已经成为一个流行词,大家对这个功能赋予很多构想,很多时 ...

  8. javascript原型链继承

    一.关于javascript原型的基本概念: prototype属性:每个函数都一个prototype属性,这个属性指向函数的原型对象.原型对象主要用于共享实例中所包含的的属性和方法. constru ...

  9. xcode7 没有Empty Application

    如果你想创建xcode6.01之前版本提供的空工程,其实很简单.1:选择模板 Single View Application2:选中 Main.storyboard,将其删除3:选择项目的 plist ...

  10. python heapq

    这个模块(build-in)实现了一个堆的数据结构,完美的解决了Top-K问题,以后解决Top-K问题的时候,直接把这个模块拿来用就可以了 注意,默认的heap是一个小顶堆! heapq模块提供了如下 ...