Java NIO服务器端开发(3)

  if(key.isAcceptable()) { ServerSocketChannel server=(ServerSocketChannel) key.channel(); SocketChannel client=server.accept(); client.configureBlocking(false); ... }

  8、将SocketChannel注册到Selector,监听OP_WRITE

  client.register(selector,SelectionKey.OP_WRITE);

  9、如果轮询的Channel为OP_WRITE,则说明要向SockChannel中写入数据,则构造ByteBuffer对象,写入数据包

  else if(key.isWritable()) { SocketChannel client=(SocketChannel) key.channel(); ByteBuffer buffer=ByteBuffer.allocate(20); String str="hello"; buffer=ByteBuffer.wrap(str.getBytes()); client.write(buffer); key.cancel(); }

  完整代码如下:

import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class ServerSocketChannelDemo { public static void main(String[] args) { ServerSocketChannel serverSocketChannel; Selector selector=null; try { serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.socket().bind(new InetSocketAddress(8080)); selector=Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } while(true) { try { //select()阻塞到至少有一个通道在你注册的事件上就绪了 //如果没有准备好的channel,就在这一直阻塞 //select(long timeout)和select()一样,除了最长会阻塞timeout毫秒(参数)。 selector.select(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } //返回已经就绪的SelectionKey,然后迭代执行 Set<SelectionKey> readKeys=selector.selectedKeys(); for(Iterator<SelectionKey> it=readKeys.iterator();it.hasNext();) { SelectionKey key=it.next(); it.remove(); try { if(key.isAcceptable()) { ServerSocketChannel server=(ServerSocketChannel) key.channel(); SocketChannel client=server.accept(); client.configureBlocking(false); client.register(selector,SelectionKey.OP_WRITE); } else if(key.isWritable()) { SocketChannel client=(SocketChannel) key.channel(); ByteBuffer buffer=ByteBuffer.allocate(20); String str="hello"; buffer=ByteBuffer.wrap(str.getBytes()); client.write(buffer); key.cancel(); } }catch(IOException e) { e.printStackTrace(); key.cancel(); try { key.channel().close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } } }

  我们用telnet localhost 8080模拟出多个客户端:

  

Java NIO服务器端开发

  程序运行结果如下:

  

Java NIO服务器端开发

三、参考资料

  1、Netty权威指南(李林峰)【Netty权威指南 PDF完整版带目录书签+源码 下载地址 

运用Spring注解实现Netty服务器端UDP应用程序 

Netty源码学习笔记

Netty使用实例

Java NIO框架--Netty4的简单示例 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/4fa3f59f8e685f1f7f0ddf0decb8f574.html