星球狂想战队|深度解读Netty:NIO那些不为人知的秘密( 六 )
获取可操作的Channel
SetselectedKeys=selector.selectedKeys();当有新增就绪的Channel , 调用select()方法 , 就会将key添加到Set集合中 。
三、代码示例前面铺垫了这么多 , 主要是想让大家能够看懂NIO代码示例 , 也方便后续大家来自己手写NIO网络编程的程序 。 创建NIO服务端的主要步骤如下:
1.打开ServerSocketChannel , 监听客户端连接
2.绑定监听端口 , 设置连接为非阻塞模式
3.创建Reactor线程 , 创建多路复用器并启动线程
4.将ServerSocketChannel注册到Reactor线程中的Selector上 , 监听ACCEPT事件
5.Selector轮询准备就绪的key
6.Selector监听到新的客户端接入 , 处理新的接入请求 , 完成TCP三次握手 , 建立物理链路
7.设置客户端链路为非阻塞模式
8.将新接入的客户端连接注册到Reactor线程的Selector上 , 监听读操作 , 读取客户端发送的网络消息
9.异步读取客户端消息到缓冲区
10.对Buffer编解码 , 处理半包消息 , 将解码成功的消息封装成Task
11.将应答消息编码为Buffer , 调用SocketChannel的write将消息异步发送给客户端
NIOServer.java:
publicclassNIOServer{privatestaticSelectorselector;publicstaticvoidmain(String[]args){init();listen();}privatestaticvoidinit(){ServerSocketChannelserverSocketChannel=null;try{selector=Selector.open();serverSocketChannel=ServerSocketChannel.open();serverSocketChannel.configureBlocking(false);serverSocketChannel.socket().bind(newInetSocketAddress(9000));serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);System.out.println("NioServer启动完成");}catch(IOExceptione){e.printStackTrace();}}privatestaticvoidlisten(){while(true){try{selector.select();IteratorkeysIterator=selector.selectedKeys().iterator();while(keysIterator.hasNext()){SelectionKeykey=keysIterator.next();keysIterator.remove();handleRequest(key);}}catch(Throwablet){t.printStackTrace();}}}privatestaticvoidhandleRequest(SelectionKeykey)throwsIOException{SocketChannelchannel=null;try{if(key.isAcceptable()){ServerSocketChannelserverSocketChannel=(ServerSocketChannel)key.channel();channel=serverSocketChannel.accept();channel.configureBlocking(false);System.out.println("接受新的Channel");channel.register(selector,SelectionKey.OP_READ);}if(key.isReadable()){channel=(SocketChannel)key.channel();ByteBufferbuffer=ByteBuffer.allocate(1024);intcount=channel.read(buffer);if(count>0){System.out.println("服务端接收请求:"+newString(buffer.array(),0,count));channel.register(selector,SelectionKey.OP_WRITE);}}if(key.isWritable()){ByteBufferbuffer=ByteBuffer.allocate(1024);buffer.put("收到".getBytes());buffer.flip();channel=(SocketChannel)key.channel();channel.write(buffer);channel.register(selector,SelectionKey.OP_READ);}}catch(Throwablet){t.printStackTrace();if(channel!=null){channel.close();}}}}NIOClient.java:
publicclassNIOClient{publicstaticvoidmain(String[]args){newWorker().start();}staticclassWorkerextendsThread{@Overridepublicvoidrun(){SocketChannelchannel=null;Selectorselector=null;try{channel=SocketChannel.open();channel.configureBlocking(false);selector=Selector.open();channel.register(selector,SelectionKey.OP_CONNECT);channel.connect(newInetSocketAddress(9000));while(true){selector.select();IteratorkeysIterator=selector.selectedKeys().iterator();while(keysIterator.hasNext()){SelectionKeykey=keysIterator.next();keysIterator.remove();if(key.isConnectable()){System.out.println();channel=(SocketChannel)key.channel();if(channel.isConnectionPending()){channel.finishConnect();ByteBufferbuffer=ByteBuffer.allocate(1024);buffer.put("你好".getBytes());buffer.flip();channel.write(buffer);}channel.register(selector,SelectionKey.OP_READ);}if(key.isReadable()){channel=(SocketChannel)key.channel();ByteBufferbuffer=ByteBuffer.allocate(1024);intlen=channel.read(buffer);if(len>0){System.out.println("["+Thread.currentThread().getName()+"]收到响应:"+newString(buffer.array(),0,len));Thread.sleep(5000);channel.register(selector,SelectionKey.OP_WRITE);}}if(key.isWritable()){ByteBufferbuffer=ByteBuffer.allocate(1024);buffer.put("你好".getBytes());buffer.flip();channel=(SocketChannel)key.channel();channel.write(buffer);channel.register(selector,SelectionKey.OP_READ);}}}}catch(Exceptione){e.printStackTrace();}finally{if(channel!=null){try{channel.close();}catch(IOExceptione){e.printStackTrace();}}if(selector!=null){try{selector.close();}catch(IOExceptione){e.printStackTrace();}}}}}}打印结果:
推荐阅读
- 游戏小怪兽|达仁星球:最新抖音直播留人控场方法和技巧
- 巅峰战队|VERTIX户外手表,勇攀新高峰——COROS
- 星球狂想战队|世界科技格局
- 家族战队|10年后退化成了“简陋版”,快看丨腾讯微博将于9月28日停服
- 路人战队|失去苹果的代价,有300万人承担不起,请别口嗨“抵制苹果”了
- 家族战队|就读懂了湖南互联网产业,读懂了这些话
- 路人战队|雷军用了什么法宝?,超越格力?新型洗烘一体机实现“弯道超车”
- NASA|NASA发现“黄金星球”,价值超万万亿美元,美国已准备前往
- 天文在线|既有大气又有水 宝藏星球土卫六,宇宙中的超级泰坦
- 通天战队|别人偷动你手机,屏幕就会一戳一个洞,只有你可以打开,教你一招