gpt4 book ai didi

java - socket 未正确关闭

转载 作者:行者123 更新时间:2023-12-03 11:52:36 25 4
gpt4 key购买 nike

我正在尝试创建一个 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 循环来关闭套接字。不过,我将如何解决这个问题?

谢谢

最佳答案

在调用接收之前,您必须添加 setSoTimeout(timeout)。这将定期抛出 SocketTimeoutExceptions,但保持数据报套接字打开。这将允许您定期检查循环变量。

此外,您应该将循环移动到第一个 try-catch 块内并添加一个 finally 块来关闭套接字。

喜欢 :

        try {
sock = new DatagramSocket(portNumber);
sock.setSoTimeout(250);
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();
}
}
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
sock.close();
}

关于java - socket 未正确关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3121574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com