执行客户端重新启动或关闭时,所有套接字连接都在服务器端的CLOSE_WAIT中挂起。 XdrAble用于将序列化数据发送到XDR流中。 pool是标准KeyedSocketPool的对象。 MAXIMUM_RETRY,MAXIMUM_RETYR_BEFORE_RESET_POOL是为重置池连接而定义的常量。 关闭连接时我错过了什么?
公共RESP电话(REQ请求,
RESP响应,int requestLength,int timeOut)抛出异常
{
套接字socket = null;
IOException ioException = null;
short attempts = 0;
boolean needResetPool = false;
while (true)
{
ioException = null;
try
{
// Get socket (open if not connected)
socket = (Socket) pool.borrowObject ();
socket.setSoTimeout (timeOut);
// Send request
BufferedOutputStream outputStream = new BufferedOutputStream (socket
.getOutputStream ());
XdrBufferEncodingStream xdrIn = new XdrBufferEncodingStream (
requestLength);
xdrIn.beginEncoding (socket.getInetAddress (), socket.getPort ());
request.xdrEncode (xdrIn);
xdrIn.endEncoding ();
outputStream.write (xdrIn.getXdrData ());
outputStream.flush ();
xdrIn.close ();
// Read response
BufferedInputStream inputStream = new BufferedInputStream (socket
.getInputStream ());
byte[] buffer = new byte[UreMsgBodyLength.MAXIMUM_MSG_LEN];
int bytesRead = inputStream.read (buffer);
if (bytesRead < UreMsgBodyLength.MESSAGE_HEADER_LEN)
throw new IOException("Socket Read Failed - invalid bytesRead="+bytesRead);
int encodedLength = bytesRead;
if ( encodedLength < 0 || ( encodedLength & 3) != 0 )
encodedLength = UreMsgBodyLength.MAXIMUM_MSG_LEN;
XdrBufferDecodingStream xdrOut = new XdrBufferDecodingStream (buffer, encodedLength);
xdrOut.beginDecoding ();
response.xdrDecode (xdrOut);
xdrOut.endDecoding ();
xdrOut.close ();
return response;
}
catch (ConnectException ex)
{
ioException = ex;
}
catch (IOException ex)
{
ioException = ex;
if (socket != null)
{
needResetPool = true;
try { socket.close (); } catch (Throwable t) {}
try
{
pool.invalidateObject (socket); // Mark the socket as invalid
}
catch (Throwable t)
{
}
socket = null;
}
}
finally
{
if (socket != null)
{
try
{
pool.returnObject (socket);
}
catch (Throwable t)
{
}
}
}
if (attempts >= MAXIMUM_RETYR_BEFORE_RESET_POOL && needResetPool)
{
pool.clear (pool.getKey ()); // clean all connect for the current server id
}
if (attempts >= MAXIMUM_RETRY)
{
throw ioException;
}
attempts++;
} // while
}
答案 0 :(得分:1)
关闭连接时我错过了什么?
服务器没有关闭其套接字以响应读取EOS(read()返回-1)。这段代码也不能很好地处理它。 CLOSE_WAIT表示对等方已关闭连接,本地系统正在等待应用程序关闭此端。