Java-Socket错误解决

作者:聂勇 欢迎转载,请保留作者信息并说明文章来源!

环境

  • 客户端 Redhat Enterprise Linux 9
  • 服务端 Redhat Enterprise Linux 9
  • JDK Javase5Update4

场景

  • 客户端每个连接池有一个keep-live的时间来控制该连接池中每一个连接的空闲生存期。
  • 服务端也有一个SocketTimeOut时间来控制每一个连接的空闲生存期。

Socket Exception

1)java.net.SocketException: Software caused connection abort: socket write error

原因:服务端将空闲超时的连接关闭了,但客户端连接池还认为连接有用,就用该连接来发送数据,所以会报错。

  • WSAECONNABORTED (10053) Software caused connection abort

A connection abort was caused internal to your host machine. The software caused a connection abort because there is no space on the socket’s queue and the socket cannot receive further connections.

WinSock description: The error can occur when the local network system aborts a connection. This would occur if WinSock aborts an established connection after data retransmission fails (receiver never acknowledges data sent on a datastream socket).

TCP/IP scenario: A connection will timeout if the local system doesn’t receive an (ACK)nowledgement for data sent. It would also timeout if a (FIN)ish TCP packet is not ACK’d (and even if the FIN is ACK’d, it will eventually timeout if a FIN is not returned).

It seems to happen more with WindowsXP and it seems also to be possibly related to Windows firewall settings. In any case the salient point is that the abort has originated inside the local machine.

It’s a stupidly worded message.

  • an intermittent router or firewall decided to drop the connection, or that some tcp/ip related malfunction occurred.

2)java.net.SocketException: Software caused connection abort: recv failed

原因:服务端将连接关闭了(可能发生了异常),但客户端还在接收数据。

3)java.net.SocketException: Broken pipe

原因:由于是长连接,所以连接会持续利用,只要连接的空闲时间没有超过keep-live的时间就认为是有效的。但服务端在客户端write date之前将连接关闭了,是因为客户端keep-live的时间和服务端SocketTimeOut的时间不一致。
出错模拟:

  1. 客户端write date
  2. 客户端wirte date
  3. 服务端 close socket
  4. 客户端write date // 客户端这时报错了

4)java.net.SocketException: Connection reset

原因:由于是长连接,所以连接会持续利用,只要连接的空闲时间没有超过keep-live的时间就认为是有效的。但服务端在客户端write date的时候将连接关闭了,是因为客户端keep-live的时间和服务端SocketTimeOut的时间不一致。

出错模拟:

  1. 客户端write date
  2. 客户端write date // 在write date的过程中,服务端关闭连接,客户端报错