gpt4 book ai didi

客户端关闭或客户端重启时,Java 服务器套接字 TCP 连接卡在 CLOSE_WAIT 状态

转载 作者:行者123 更新时间:2023-11-30 11:21:07 29 4
gpt4 key购买 nike

在执行客户端重启或关闭时,所有套接字连接都卡在服务器端的 CLOSE_WAIT 中。XdrAble 用于将序列化数据发送到 XDR 流中。pool 是标准 KeyedSocketPool 的对象。MAXIMUM_RETRY、MAXIMUM_RETYR_BEFORE_RESET_POOL 是定义为重置池连接的常量。关闭连接时我错过了什么?

公共(public) RESP 调用(REQ 请求, RESP 响应,int requestLength,int timeOut)抛出异常 {
套接字套接字=空;

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

最佳答案

What am I missing while closing the connections?

服务器没有关闭其套接字以响应读取 EOS(read() 返回 -1)。这段代码也处理不好。 CLOSE_WAIT 表示对端已关闭连接,本地系统正在等待应用程序关闭此端。

关于客户端关闭或客户端重启时,Java 服务器套接字 TCP 连接卡在 CLOSE_WAIT 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22385057/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com