packagecom.tz.simple.tcp;importjava.net.InetSocketAddress;importjava.nio.ByteBuffer;importjava.nio.channels.SelectionKey;importjava.nio.channels.Selector;importjava.nio.channels.ServerSocketChannel;importjava.nio.channels.SocketChannel;importjava.util.Iterator;importjava.util.Set;importcom.tz.uitl.Common;/*** 非阻塞式TCP时间服务器
*
*@authorLJZ
**/publicclassNIOTCPTimeServerextendsThread {privateintlistenPort=8485;privateServerSocketChannel serverSocket=null;privateSelector acceptSelector=null;privateSelector readSelector=null;publicNIOTCPTimeServer(intp) {
listenPort=p;try{
acceptSelector=Selector.open();
readSelector=Selector.open(); serverSocket=ServerSocketChannel.open();
serverSocket.configureBlocking(false);
serverSocket.socket().bind(newInetSocketAddress(listenPort));
serverSocket.register(acceptSelector, SelectionKey.OP_ACCEPT);
System.out.println("服务器启动成功, 监听端口 ["+listenPort+"]");newReadThread().start();
}catch(Exception e) {
System.out.println("服务器启动失败!");
e.printStackTrace();
}
}/*** 主线程方法只处理客户端连接
* 同时将连接客户端事件响应注册为读响应*/publicvoidrun() {while(true) {try{if(acceptSelector.select(100)>0) {
Set keys=acceptSelector.selectedKeys();for(Iterator i=keys.iterator(); i.hasNext();) {
SelectionKey key=(SelectionKey) i.next();
i.remove();
ServerSocketChannel readyChannel=(ServerSocketChannel) key
.channel();
SocketChannel incomingChannel=readyChannel.accept();
System.out.println("客户端 ["+incomingChannel.socket()
.getRemoteSocketAddress()+"] 与服务器建立连接.");
incomingChannel.configureBlocking(false);
incomingChannel.register(readSelector,
SelectionKey.OP_READ,newStringBuffer());
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
}/*** 客户端数据读线程
*
*@authorLJZ
**/privateclassReadThreadextendsThread {publicvoidrun() {intkeysReady=-1;while(true) {try{/*** 检查客户数据事件,超时1秒*/keysReady=readSelector.select(100);if(keysReady>0) {
Set readyKeys=readSelector.selectedKeys();for(Iterator i=readyKeys.iterator(); i.hasNext();) {
SelectionKey key=(SelectionKey) i.next();
SocketChannel incomingChannel=(SocketChannel) key
.channel();
readData(incomingChannel);
i.remove();
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
}privatevoidreadData(SocketChannel channel) {try{
ByteBuffer readBuf=ByteBuffer.allocate(1024);if(channel.read(readBuf)>0) {
readBuf.flip();
System.out.println("收到客户端 ["+channel.socket().getRemoteSocketAddress()+"] 数据 ["+Common.decode(readBuf)+"].");
}
}catch(Exception e) {try{
channel.close();
System.out.println("关闭一个终端.");
}catch(Exception ex) {
}
}
}
}/***@paramargs*/publicstaticvoidmain(String[] args) {try{newNIOTCPTimeServer(8485).start();
}catch(Exception e) {
}
}
}