I need to know how to stop thread in this program:
public class MasterServerThread extends Thread{
private Socket socket = null;
private MasterServer server = null;
private int clientID = -1;
private BufferedReader streamInput = null;
private PrintWriter streamOutput = null;
public MasterServerThread(MasterServer _server, Socket _socket){
server = _server;
socket = _socket;
clientID = _socket.getPort();
}
public void run(){
server.Log("Server Thread " +clientID + " running");
while(true){
String test;
try {
test = streamInput.readLine();
System.out.println("Client "+clientID+": "+test);
} catch (IOException e) {
System.out.println(clientID+ " Error reading: "+e.getMessage());
}
server.handleClient(clientID, "test");
}
}
}
This is my server thread code. When my client terminates itself, I get an endless loop of errors:
53088 Error reading: Connection reset 0
I know something needs to be done here, but I don't know what, exactly:
try {
test = streamInput.readLine();
System.out.println("Client "+clientID+": "+test);
} catch (IOException e) {
System.out.println(clientID+ " Error reading: "+e.getMessage());
}
You should handle your IOException
better and just return (or break) out of the while(true)
loop. I'm not sure there is any case that you want to continue to run reading from an BufferedReader
after it threw such an exception.
try {
test = streamInput.readLine();
System.out.println("Client "+clientID+": "+test);
} catch (IOException e) {
System.out.println(clientID+ " Error reading: "+e.getMessage());
// you need the return line here -- or a break
return;
}
在连接重置的情况下,最好的选择是从run
方法返回,这将停止一个线程。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.