java.net.SocketException:连接重置。我怎么阻止这个?

时间:2014-05-19 05:31:41

标签: java sockets exception tcp

每次关闭我的TCP服务器时,在我的客户端上,我都会遇到此异常:

    java.net.SocketException: Connection reset
      at java.net.SocketInputStream.read(SocketInputStream.java:196)
      at java.net.SocketInputStream.read(SocketInputStream.java:122)
      at java.net.SocketInputStream.read(SocketInputStream.java:210)
      at java.io.ObjectInputStream$PeekInputStream.peek(ObjectInputStream.java:2293)
      at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(ObjectInputStream.java:2473)
      at java.io.ObjectInputStream$BlockDataInputStream.refill(ObjectInputStream.java:2543)
      at java.io.ObjectInputStream$BlockDataInputStream.read(ObjectInputStream.java:2615)
      at java.io.ObjectInputStream$BlockDataInputStream.readByte(ObjectInputStream.java:2764)
      at java.io.ObjectInputStream.readByte(ObjectInputStream.java:916)
      at client.ListenFromServer.run(ListenFromServer.java:33)

这是我的两段代码,一段是我的TCPClient,它通过套接字连接到服务器,还创建一个侦听器来监听来自服务器的消息:

TCPClient.java: http://pastie.org/private/msbnuhxyevxjlsdq1wvhow

ListenForServer.java: http://pastie.org/private/pav4azrakgfz31culrrg2a

如何阻止此异常发生?在我在ListenForServer.java中的while循环中,我检查套接字是否已关闭,如果是,我打破了循环,但我仍然遇到此异常。

捕获它的最佳方法是什么,因为当我退出它时我的程序没有正确关闭,我必须在Netbeans IDE中手动关闭它。

1 个答案:

答案 0 :(得分:2)

 In my while loop in ListenForServer.java, I make a check to see if the socket is closed, and if it is, I break out of the loop, yet I'm still getting this exception.

是的,但是当套接字关闭时你仍然在听取输入流。

您需要捕获套接字异常或在循环时更改您的