java socket异步接收数据_Java TCP异步数据接收
/*** TcpAsyncServer.java*/
引入java.nio库中的ByteBuffer
port类型的整数值被初始化为6000;/缓冲区大小/分配容量为1024的ByteBuffer对象被赋值给buffer;/其它相关定义/选择器被赋值为一个空对象;
ServerSocketChannel channel;
ServerSocket socket;/启动/
public void Start() throws Exception {/创建一个Selector实例/}
selector = new Selector().open();
/建立通道连接并配置为无阻塞模式/
channel = new ServerSocketChannel().open();
channel.configureBlockingMode(BLOCKING_MODE_NON-blocking);
/指定本地主机地址/
localHost = "localhost";
//InetAddress ip = InetAddress.getByName("127.0.0.1");
InetAddress ip =InetAddress.getLocalHost();
System.out.print(ip.toString());/绑定IP和端口/In boxed target address = new boxed(target, port);
socket=channel.socket();
socket.bind(address);/启动监听/System.out.println("TCP服务器开始监听...");
Listen();
}/停止/
public void Stop() throwsException {
channel.close();
selector.close();
}/监听/
public void Listening() throws Exception {/注册接收事件的操作/} channel.register(selector, SelectionKey.OP_ACCEPT); /进入无限循环/
while (true) {
执行选中操作;/轮询事件/通过调用selector.selectedKeys().iterator()生成迭代器;当迭代器存在时循环处理;
SelectionKey key=(SelectionKey)iter.next();
iter.remove();/事件分类处理/
if(key.isAcceptable()) {
ServerSocketChannel ssc=(ServerSocketChannel)key.channel();
SocketChannel sc=ssc.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
System.out.println("新终端已连接:"+sc.getRemoteAddress());
}else if(key.isReadable()) {
通过类型转换将key.channel()赋值给变量sc;接收缓冲区中的数据到整数变量recvCount;如果接收到的数据量大于零时进入{}中的操作;如果接收到的数据量大于零时,将接收到的数据存储在名为arr的字节数组中;
System.out.println(sc.getRemoteAddress()+ "发来数据: "+ newString(arr));
buffer.flip();
}else{
sc.close();
}
buffer.clear();
}else{
}
}
}
}
}
