如何关闭 运行 套接字线程?
how to close a running socket thread?
我是运行一台启用多套接字连接的服务器。
我试图在客户端终止连接时关闭线程。
这是客户端线程的代码:
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
语句并不能解决问题。该线程仍然 运行 并尝试从套接字中获取 send/read 数据。
如何让它发挥作用?我错过了什么?
任何帮助,将不胜感激。谢谢你。
isInputShutdown()
告诉你你是否关闭了这个socket的输入。跟同行没关系。
您的问题是您忽略了 read()
方法的结果。如果它returns -1,对端已经关闭了连接。
注意您对 available()
的使用也不正确。只需读入固定大小的缓冲区。
您可以大大简化您的代码。
我是运行一台启用多套接字连接的服务器。 我试图在客户端终止连接时关闭线程。
这是客户端线程的代码:
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
语句并不能解决问题。该线程仍然 运行 并尝试从套接字中获取 send/read 数据。
如何让它发挥作用?我错过了什么?
任何帮助,将不胜感激。谢谢你。
isInputShutdown()
告诉你你是否关闭了这个socket的输入。跟同行没关系。
您的问题是您忽略了 read()
方法的结果。如果它returns -1,对端已经关闭了连接。
注意您对 available()
的使用也不正确。只需读入固定大小的缓冲区。
您可以大大简化您的代码。