gpt4 book ai didi

Java 消息被发送到一个关闭的套接字

转载 作者:行者123 更新时间:2023-11-30 10:51:39 25 4
gpt4 key购买 nike

我有一个客户端程序,可以将在控制台中输入的消息发送到服务器。根据一些建议,我引入了使用 Socket.checkError() 检查已关闭的套接字。尽管如此,出于某种原因,它仅在第二次尝试发送消息失败后才指示错误。

我的代码:

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
while (true)
try (
Socket clientSocket = new Socket(hostname, port);
PrintWriter socketOut = new PrintWriter(clientSocket.getOutputStream(), true);
) {
String input;
while ((input=stdIn.readLine())!=null) {
socketOut.println(input);
if (socketOut.checkError()) {
System.out.println("Got socket error");
break;
}
}
} catch (IOException e) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {}
}

我在收到“消息 1”后(手动)关闭了我的服务器端。因此,我希望在尝试发送下一条消息时收到错误消息。尽管如此,它只在一条消息之后出现:

message1
message2
message3
Got socket error

任何人都可以解释这种行为并告诉我一种在第一次尝试发送无效消息时立即获得通知的方法吗?

最佳答案

Following some advices, I introduced a check for a closed socket with Socket.checkError().

没有这样的方法。显然,您指的是 PrintWriter.checkError()。

Nevertheless, for some reason it indicates error only after second failed attempt to send a message.

原因是在发送方有一个套接字发送缓冲区,在接收方有一个套接字接收缓冲区,并且发送是异步的:因此第一次发送不可能检测到错误。

Can anyone explain this behavior and advise me a method to get notification right on the first attempt to send a message in void?

没有一个。这就是 TCP 的本质。您正在尝试的内容表明应用程序协议(protocol)错误,答案也存在于应用程序协议(protocol)领域:不要让对等方关闭套接字,而这一端仍然可以发送数据,在对等方通过应用程序协议(protocol)表明不再读取任何数据后,不允许此端发送数据。

不要在网络上使用 PrintWriter。它抑制了实际的异常。使用 BufferedWriter 以及 write()newLine() 方法。

关于Java 消息被发送到一个关闭的套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34630065/

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