我正在运行一个启用多个套接字连接的服务器。我正在尝试在客户端终止连接时关闭线程。
这是客户端线程的代码:
class ClientThread implements Runnable {
Socket threadSocket;
private boolean chk = false, stop = false, sendchk = false, running = true;
DataOutputStream out = null;
//This constructor will be passed the socket
public ClientThread(Socket socket){
threadSocket = socket;
}
public void run()
{
System.out.println("New connection at " + new Date() + "\n");
try {
DataInputStream in = new DataInputStream (threadSocket.getInputStream());
out = new DataOutputStream (threadSocket.getOutputStream());
while (running){
// read input from client
int ln = in.available();
byte [] bytes = new byte [ln];
in.read(bytes);
String msg = new String(bytes);
// parse in going message
messageParsing(msg);
// respond to client
response();
/////////////////////////////
////// this is the part that i thought would help me close the thread
////////////////////////////
if (threadSocket.isInputShutdown()){
running = false;
}
}
}
catch (IOException ex) {System.out.println(ex);}
finally {
try {
threadSocket.close();
System.out.println("Connection closed due to unauthorized entry.\n");
} catch (IOException ex) {System.out.println(ex);}
}
}}
但是,该if
语句不能解决问题。该线程仍在运行,并尝试从套接字发送/读取数据。如何使其工作?我想念什么?任何帮助,将不胜感激。谢谢你。
isInputShutdown()
告诉你无论你有关闭此套接字的输入。它与同位体没有任何关系。
您的问题是您忽略了该read()
方法的结果。如果返回-1,则表明对等方已关闭连接。
注意您的使用available()
也不正确。只需读入固定大小的缓冲区即可。
您可以大大简化您的代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句