gpt4 book ai didi

java - 关闭套接字连接

转载 作者:行者123 更新时间:2023-12-02 00:31:33 24 4
gpt4 key购买 nike

我有 2 个线程运行聊天程序,其中一个是服务器,另一个是客户端,一切正常,直到我单击退出按钮。

由于单击“退出”按钮的线程的套接字在其他套接字尝试读取数据时异步关闭,因此/living 线程中的读取套接字会受到关闭的干扰并引发错误 mssg,而预期也正确关闭它自己的套接字并安静地死去。

我需要建议来克服这个问题...

这是我收到的错误消息:

java.net.SocketException: socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at chatSockets.ChatClient.run(ChatClient.java:56)
at java.lang.Thread.run(Unknown Source)

这就是代码:

public void run() {
try {
if (type==Type.CLIENT) {
socket = new Socket(HOST, PORT);
} else {
ServerSocket ss = new ServerSocket(PORT);
socket = ss.accept();
}
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));

while (!socket.isInputShutdown()) {
chat.append(in.readLine()+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void actionPerformed(ActionEvent e) {
String s = name + " : " + chat.getMssg();
JButton src=(JButton)e.getSource();
if (src.getText()=="Quit") {
out.close();
try {
in.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
else {
out.println(s);
chat.append(s + "\n");
chat.clearPanel();
}

}

最佳答案

这是预期的行为。只需在 catch block 中处理另一端套接字的关闭并继续执行即可。

来自javadoc:

public String readLine()
throws IOException

Read a line of text. A line is considered to be terminated by any one of a
line feed ('\n'), a carriage return ('\r'), or a carriage return followed
immediately by a linefeed.

Returns:
A String containing the contents of the line, not including any
line-termination characters, or null if the end of the stream has been
reached
Throws:
IOException - If an I/O error occurs

因此,这里有两个选择:要么依赖于当另一端关闭套接字并在 catch block 中进行清理时抛出 IOException 的事实,要么如果您想要一种干净的关闭方式down 向另一个线程发送一个特殊的“停止 token ”,表明您正在退出并且它应该关闭其末端的套接字。

关于java - 关闭套接字连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8941413/

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