什么时候抛出“java.io.IOException:Connection reset by peer”?

ERROR GServerHandler - java.io.IOException: Connection reset by peer java.io.IOException: Connection reset by peer at sun.nio.ch.FileDispatcher.read0(Native Method) at sun.nio.ch.SocketDispatcher.read(Unknown Source) at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source) at sun.nio.ch.IOUtil.read(Unknown Source) at sun.nio.ch.SocketChannelImpl.read(Unknown Source) at org.jboss.netty.channel.socket.nio.NioWorker.read(NioWorker.java:323) at org.jboss.netty.channel.socket.nio.NioWorker.processSelectedKeys(NioWorker.java:282) at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:202) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) 

此日志来自使用netty实现的游戏服务器。 什么可以导致这个例外?

java.io.IOException:由peer重置连接

另一方在交易中突然中止了连接。 这可能有许多原因,无法从服务器端控制。 例如,最终用户决定关闭客户端或突然更改服务器,同时仍与服务器交互,或客户端程序崩溃,或最终用户的Internet连接中断,或最终用户的计算机崩溃等等。

为了扩展BalusC的答案,在对等体停止读取并关闭其套接字之后发送者继续写入的任何情况都将产生此exception。 换句话说,应用程序协议错误。 例如,如果你向同伴写了一些对手不理解的东西,然后它关闭了它的套接字以抗议,然后你继续写,对等的TCP堆栈将发出一个RST,这会导致这个exception和消息在发件人。

Netty中的java.io.IOException意味着您的游戏服务器尝试将数据发送到客户端,但该客户端已关闭与您的服务器的连接。

而这个例外不是唯一的例外! 还有其他几个。 请参阅Xitrum中的BadClientSilencer。 我必须添加它以防止这些错误弄乱我的日志文件。

对我来说,有用的代码女巫帮助我http://rox-xmlrpc.sourceforge.net/niotut/src/NioServer.java

//远程强制关闭连接,取消

//选择键并关闭频道。

  private void read(SelectionKey key) throws IOException { SocketChannel socketChannel = (SocketChannel) key.channel(); // Clear out our read buffer so it's ready for new data this.readBuffer.clear(); // Attempt to read off the channel int numRead; try { numRead = socketChannel.read(this.readBuffer); } catch (IOException e) { // The remote forcibly closed the connection, cancel // the selection key and close the channel. key.cancel(); socketChannel.close(); return; } if (numRead == -1) { // Remote entity shut the socket down cleanly. Do the // same from our end and cancel the channel. key.channel().close(); key.cancel(); return; } ... 

有很多因素,首先看服务器是否返回结果,然后在服务器和客户端之间进行检查。

首先从服务器端纠正它们,然后检查服务器和客户端之间的写入条件!

服务器端从客户端纠正数据层和服务器之间的超时,纠正超时和可用连接数量!

我认为这应该是java.net.SocketException,因为它的定义是针对TCP错误而声明的。

 /** * Thrown to indicate that there is an error in the underlying * protocol, such as a TCP error. * * @author Jonathan Payne * @version %I%, %G% * @since JDK1.0 */ public class SocketException extends IOException {