我正在尝试创建一个 UDP 监听器,它将在单独的线程上监听。第一次它工作正常,但是当我停止连接然后再次启动它时,它会出现错误。
listenerRunnable = new Runnable() {
public void run() {
//This thread will listen keep listening to the UDP traffic and put it to the log source string
try {
sock = new DatagramSocket(portNumber);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(keepListening) {
try {
pack = new DatagramPacket(recievedData, BUFFERSIZE);
sock.receive(pack);
String data = new String(pack.getData(), 0, pack.getLength());
addToLog(data);
System.out.println(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sock.close();
}
}
};
/**
* Function to start the listening thread.
*/
public void startListening(int portNum) {
keepListening = true;
portNumber = portNum;
listenerThread = new Thread(listenerRunnable);
logSource_buffer = "";
logSourcehtml_buffer = "";
logSourcehtml_temp = "";
ipListIndex_beg = 0;
ipListIndex_end = -1;
if(!listenerThread.isAlive()) {
listenerThread.start();
}
}
/**
* stops the listening thead. When the listening thread sees that keepListening is set to false
* it will reach the end of its loop, close the socket, and the thread will die.
*/
public void stopListening() {
keepListening = false;
}
它给了我以下错误:
logUpdatingThread has entered synchronized block!!! java.net.SocketException: Unrecognized Windows Sockets error: 0: Cannot bind at java.net.PlainDatagramSocketImpl.bind0(Native Method) at java.net.PlainDatagramSocketImpl.bind(Unknown Source)
指向 sock.recieve(pack) 行; 似乎由于某种原因,套接字没有关闭,因为我认为,它在 sock.recieve(pack) 处等待,并且永远不会退出 while 循环来关闭套接字。我该如何解决这个问题?
谢谢
最佳答案
正如 Peter Tillemans 所说,您应该设置接收超时,这样您就不会永远坐在那里尝试 receive()。
此外,保留由 new Thread(listenerRunnable)
返回的 Thread 对象,以便您的 stopListening() 方法可以等待线程终止:
public void stopListening() {
keepListening = false;
listenerThread.join();
}
关于java - 套接字未正确关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3121574/