我在StackOverflow和Google上查找了许多,但未能找到解决我的问题的方法。这里是我正在做的事情。
我有一个控制台应用程序的服务器,用户使用任何Telnet客户端连接到它。我使用三个单独的线程来处理客户机,一个线程(ClientThread)控制对客户机的所有程序访问,ClientThread维护两个线程,一个用于处理输入,一个用于发送输出。ClienThread读取客户端套接字并将输入(如果有的话)发送到ProcessingThread,该线程处理输入并执行用户指定的操作。输出线程管理需要发送的输出队列,并在每次唤醒时发送它。当用户断开连接时,我偶尔会使用位于输出"队列"中的输出,直到连接被终止为止,因此我想设置连接保持活动状态,直到输出队列为空。然而,读取套接字的线程(最终关闭它),现在阻塞在读取时,我无法关闭它。以前当用户断开连接时,我只需关闭套接字,这不是问题。下面是相关代码。
我有一个控制台应用程序的服务器,用户使用任何Telnet客户端连接到它。我使用三个单独的线程来处理客户机,一个线程(ClientThread)控制对客户机的所有程序访问,ClientThread维护两个线程,一个用于处理输入,一个用于发送输出。ClienThread读取客户端套接字并将输入(如果有的话)发送到ProcessingThread,该线程处理输入并执行用户指定的操作。输出线程管理需要发送的输出队列,并在每次唤醒时发送它。当用户断开连接时,我偶尔会使用位于输出"队列"中的输出,直到连接被终止为止,因此我想设置连接保持活动状态,直到输出队列为空。然而,读取套接字的线程(最终关闭它),现在阻塞在读取时,我无法关闭它。以前当用户断开连接时,我只需关闭套接字,这不是问题。下面是相关代码。
public class ClientThread extends Thread {
// Initialization and other code not pertaining to the problem
public void run() {
while (connected) {
try {
String input = in.readLine();
if (input != null) {
processor.queue(TextUtility.processBackspaceChars(input));
timeoutTimer.interrupt();
}
} catch (Exception e) {
if (e.getMessage() != null && !(e.getMessage().equals("socket closed")))
server.appendError("Issue reading from client: "
+ getClientDisplayInfo() + "\n"
+ "&r-The issue is:&w- " + e.getMessage() + "&r-.");
}
}
while (disconnecting) {
try {
if (outputThread.hasOutput()) {
sleep(10);
} else {
disconnecting = false;
outputThread.disconnect();
client.close();
}
} catch (Exception exc) {
server.appendError("Failed to close the Thread for client: " + getClientDisplayInfo());
}
}
}
public void disconnect() {
try {
connected = false;
disconnecting = true;
processor.disconnect();
timeoutTimer.disconnect();
in.close(); // This is the BufferedReader that reads the Socket Input Stream
this.interrupt(); // This was my attempt to break out of the read, but it failed
} catch (Exception e) {
server.appendError("Failed to close the Thread for client: "
+ getClientDisplayInfo());
}
}
}
我只是好奇如何在不关闭Socket的情况下取消读取,因为我需要继续发送输出。