Skip to content

Commit

Permalink
[miio] fix port leak - max datagram sockets reached (openhab#8189)
Browse files Browse the repository at this point in the history
Fix Max Datagram connections reached issue
Possibly also addressing openhab#8091 as exception during closing would prevent
thread closing

Signed-off-by: Marcel Verpaalen <marcel@verpaalen.com>
  • Loading branch information
marcelrv authored and markus7017 committed Sep 18, 2020
1 parent 6a8faad commit d0ad324
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -239,9 +239,10 @@ private synchronized void startReceiverThreat() {
*/
private synchronized void stopReceiverThreat() {
if (socketReceiveThread != null) {
closeSocket();
socketReceiveThread.interrupt();
socketReceiveThread = null;
}
closeSocket();
}

/**
Expand All @@ -266,7 +267,7 @@ public void run() {
private void receiveData(DatagramSocket socket) {
DatagramPacket receivePacket = new DatagramPacket(new byte[BUFFER_LENGTH], BUFFER_LENGTH);
try {
while (true) {
while (!interrupted()) {
logger.trace("Thread {} waiting for data on port {}", this, socket.getLocalPort());
socket.receive(receivePacket);
String hostAddress = receivePacket.getAddress().getHostAddress();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,8 @@ public synchronized void startReceiver() {
if (senderThread == null || !senderThread.isAlive()) {
senderThread = new MessageSenderThread();
senderThread.start();
this.senderThread = senderThread;
}
this.senderThread = senderThread;
}

/**
Expand Down Expand Up @@ -244,6 +244,7 @@ public void run() {
logger.warn("Error while polling/sending message", e);
}
}
closeSocket();
logger.debug("Finished Mi IO MessageSenderThread");
}
}
Expand Down Expand Up @@ -375,6 +376,8 @@ private DatagramSocket getSocket() throws SocketException {
if (socket == null || socket.isClosed()) {
socket = new DatagramSocket();
socket.setSoTimeout(timeout);
logger.debug("Opening socket on port: {} ", socket.getLocalPort());
this.socket = socket;
return socket;
} else {
return socket;
Expand All @@ -383,17 +386,27 @@ private DatagramSocket getSocket() throws SocketException {

public void close() {
try {
final DatagramSocket socket = this.socket;
if (socket != null) {
socket.close();
}
final MessageSenderThread senderThread = this.senderThread;
if (senderThread != null) {
senderThread.interrupt();
}
} catch (SecurityException e) {
logger.debug("Error while closing: {} ", e.getMessage());
}
closeSocket();
}

public void closeSocket() {
try {
final DatagramSocket socket = this.socket;
if (socket != null) {
logger.debug("Closing socket for port: {} ", socket.getLocalPort());
socket.close();
this.socket = null;
}
} catch (SecurityException e) {
logger.debug("Error while closing: {} ", e.getMessage());
}
}

/**
Expand Down

0 comments on commit d0ad324

Please sign in to comment.