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