gpt4 book ai didi

java - 客户端断开连接时线程异常

转载 作者:行者123 更新时间:2023-12-02 07:56:50 25 4
gpt4 key购买 nike

当客户端使用 CTRL-C 断开连接或连接终止时,服务器应该生成一条消息,表明它已这样做,而不是生成如下异常:

Exception in thread "Thread-1" java.lang.NullPointerException at ChatServerThread.handleClient(ChatServerThread.java:31) at ChatServerThread.run(ChatServerThread.java:17)

在我分别从 read/writeUTF() 转换为 readLine() 和 writeByte() 并让服务器用客户端发送的内容响应客户端后,它开始表现出这种行为。请参阅Exception in thread了解详情。

问题是如何让 EOFException 功能再次工作,以便客户端关闭连接。 打印异常消息。第 31 行是 if( nextCommand.equals(".bye") ) {

import java.net.*;
import java.io.*;

//public class ChatServerThread implements Runnable
public class ChatServerThread extends Thread
{ private Socket socket = null;
private ChatServer server = null;
private int ID = -1;
private BufferedReader streamIn = null;
private DataOutputStream streamOut = null;

public ChatServerThread(ChatServer _server, Socket _socket)
{ server = _server; socket = _socket; ID = socket.getPort();
}
public void run() {
try {
handleClient();
} catch( EOFException eof ) { \\This does not seem to be working now and it previously was
System.out.println("Client closed the connection.");
} catch( IOException ioe ) {
ioe.printStackTrace();
}
}

public void handleClient() throws IOException {
boolean done = false;
try {
System.out.println("Server Thread " + ID + " running.");
while (!done) {
String nextCommand = streamIn.readLine();
if( nextCommand.equals(".bye") ) {
System.out.println("Client disconnected with bye.");
done = true;
} else {
System.out.println( nextCommand );
String nextReply = "You sent me: " + nextCommand.toUpperCase() + '\n';
streamOut.writeBytes ( nextReply );
}
}
} finally {
streamIn.close();
streamOut.close();
socket.close();
}
}
public void open() throws IOException
{
streamIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
streamOut = new DataOutputStream(socket.getOutputStream());
}
public void close() throws IOException
{ if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
if (streamOut != null) streamOut.close();
}
}

最佳答案

第二行抛出异常:

String nextCommand = streamIn.readLine();
if( nextCommand.equals(".bye") ) {

显然nextCommandnullstreamInBufferedReader ,引用 readLine() 的 JavaDoc :

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

DataInputStream.readUTF() 相比,这是不同的行为:

Returns:

a Unicode string.

Throws:

EOFException - if this input stream reaches the end before reading all the bytes.

我的猜测是 Ctrl + C 会中断阻塞 readLine() 并发出流结束信号。

关于java - 客户端断开连接时线程异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9507349/

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