gpt4 book ai didi

java - 具有正常关闭功能的 AsynchronousServerSocketChannel

转载 作者:行者123 更新时间:2023-11-30 03:13:52 25 4
gpt4 key购买 nike

my previous Question我问如何实现正确的多线程服务器。我得到了编程“正常关闭”的回复,我尝试这样做。然而,这并没有奏效。我在客户端仍然有处于 TIME_WAIT 状态的打开套接字。

客户:

private <T extends Serializable> T sendCommand(final Command<T> command) throws ExecutionException, InterruptedException, IOException, ClassNotFoundException {
T result = null;

try (final AsynchronousSocketChannel channel = AsynchronousSocketChannel.open(channelGroup)) {
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.connect(this.mwInfo.getNextMiddleware()).get();

final OutputStream os = Channels.newOutputStream(channel);
final InputStream is = Channels.newInputStream(channel);
final ObjectOutputStream oos = new ObjectOutputStream(os);

oos.writeObject(command);
oos.flush();
channel.shutdownOutput();

final ObjectInputStream ois = new ObjectInputStream(is);
result = (T) ois.readObject();

while(ois.read() != -1){
System.out.println("busy");
}

try{
channel.shutdownInput();
}catch(Exception ex){
ex.printStackTrace();
}

oos.close();
ois.close();
}

return result;
}

服务器:

this.asyncSocket.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
@Override
public void completed(final AsynchronousSocketChannel result, Void attachment) {
asyncSocket.accept(null, this);

exec.submit(new Runnable() {
@Override
public void run() {
Command cmd = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;

try {
ois = new ObjectInputStream(Channels.newInputStream(result));
cmd = (Command) ois.readObject();

while(ois.read() != -1){
System.out.println("busy");
}

result.shutdownInput();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

try{
oos = new ObjectOutputStream(Channels.newOutputStream(result));
oos.writeObject("test"); //do some other work here..
oos.flush();
result.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}

try {
oos.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
}

try {
result.close();
}catch (IOException ex){
ex.printStackTrace();
}
}
});
}

@Override
public void failed(Throwable exc, Void attachment) {
}
});

有人知道为什么这不是正常关闭吗?它看起来结构不太好,因为我正在玩 try-catch block ..

提前致谢!

最佳答案

I still have open sockets in TIME_WAIT state on the client side.

您将始终在一侧或另一侧的 TIME_WAIT 中拥有套接字,并且客户端是您想要它们的位置,而不是服务器端。

状态在 2*MSL 后过期,这意味着两个最大段生存期,即两倍两分钟。

这里没有需要解决的问题。

关于java - 具有正常关闭功能的 AsynchronousServerSocketChannel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33070988/

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