客户端主动断开与服务端的连接,但是如果客户端掉线,服务端就接收不到了。。
异常信息
java.io.IOException: Connection reset by peer at java.base/sun.nio.ch.FileDispatcherImpl.read0(Native Method) at java.base/sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39) at java.base/sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:276) at java.base/sun.nio.ch.IOUtil.read(IOUtil.java:245) at java.base/sun.nio.ch.IOUtil.read(IOUtil.java:223) at java.base/sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:358) at space.pankui.nio.chat.ChatNIOServer.read(ChatNIOServer.java:123) at space.pankui.nio.chat.ChatNIOServer.start(ChatNIOServer.java:100) at space.pankui.nio.chat.ChatNIOServer.main(ChatNIOServer.java:27)客户端掉线了....
/** * 读取客户端消息 */ private String read(SelectionKey key) { SocketChannel socketChannel = (SocketChannel) key.channel(); String readResult = "客户端发送信息:"; try { ByteBuffer readBuffer = ByteBuffer.allocate(256); socketChannel.configureBlocking(false); int read = 0; try { read = socketChannel.read(readBuffer); } catch (IOException e) { System.out.println("客户端掉线了...."); // https://stackoverflow.com/questions/8658118/when-is-java-io-ioexceptionconnection-reset-by-peer-thrown // The remote forcibly closed the connection, cancel // the selection key and close the channel. // 需要在这里做判断 key.cancel(); socketChannel.close(); return "客户端掉线"; } //这个方法只能侦测到客户端主动断开与服务端的连接,但是如果客户端掉线,服务端就接收不到 if (read == -1) { socketChannel.close(); key.cancel(); } readBuffer.flip(); String result = new String(readBuffer.array(), StandardCharsets.UTF_8).trim(); System.out.println("客户端发送信息:" + result); return readResult + result; } catch (IOException e) { e.printStackTrace(); } return readResult; }
注意 如果你的代码有读和写,在客户端掉线之后
key.cancel(); socketChannel.close();
当你在之后还有调用 SelectionKey 需要判断是否 有效。
while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); iterator.remove(); // 每个都需要判断是否有效,因为客户端可能掉线了,然后就释放了 if (selectionKey.isValid() && selectionKey.isAcceptable()) { this.accept(selectionKey); } if (selectionKey.isValid() && selectionKey.isReadable()) { this.read(selectionKey); } if (selectionKey.isValid() && selectionKey.isWritable()) { this.write(selectionKey); } }
参考
下面这里给的方法解决不了客户端掉线问题
代码来源: