Netty学习4—NIO服务端报错 远程主机强迫关闭了一个现有的连接

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

1 发现问题

NIO编程中服务端会出现报错

Exception in thread "main" java.io.IOException: 远程主机强迫关闭了一个现有的连接。 at sun.nio.ch.SocketDispatcher.read0(Native Method) at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:25) at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:233) at sun.nio.ch.IOUtil.read(IOUtil.java:206) at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:207) at com.rb.socket.nio.server.n.NIOServer.handleKey(NIOServer.java:87) at com.rb.socket.nio.server.n.NIOServer.listen(NIOServer.java:57) at com.rb.socket.nio.server.n.NIOServer.main(NIOServer.java:122)
主要原因是客户端强制关闭了连接(没有调用SocketChannel的close方法),服务端还在read事件中,此时读取客户端的信息时会报错。

2 解决问题

服务器读取事件增强健壮性:

 public void handelerRead(SelectionKey key) throws IOException {  // 服务器可读取消息:得到事件发生的Socket通道  SocketChannel channel = (SocketChannel) key.channel();  // 创建读取的缓冲区  ByteBuffer buffer = ByteBuffer.allocate(1024);  int read = channel.read(buffer);  if (read > 0) {   byte[] data = buffer.array();   String msg = new String(data).trim();   System.out.println("服务端收到信息:" + msg);   // 回写数据, 将消息回送给客户端   ByteBuffer outBuffer = ByteBuffer.wrap("好的".getBytes());   channel.write(outBuffer);  } else {   System.out.println("客户端关闭");   key.cancel();  } }


原贴地址:http://www.myexception.cn/program/1059786.html

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/hdsghtj/article/details/84062419