Skip to content

Commit 8a1dde6

Browse files
Rewrite server core loop
* Handle socket timeout * Remove the pointless threads list * Start the server on its own thread
1 parent 99aeae4 commit 8a1dde6

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

src/ros_tcp_endpoint/server.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import socket
1717
import json
1818
import sys
19+
import threading
1920

2021
from .tcp_sender import UnityTcpSender
2122
from .client import ClientThread
@@ -51,6 +52,12 @@ def __init__(self, node_name, buffer_size=1024, connections=10):
5152
self.syscommands = SysCommands(self)
5253

5354
def start(self):
55+
server_thread = threading.Thread(target=self.listen_loop)
56+
# Exit the server thread when the main thread terminates
57+
server_thread.daemon = True
58+
server_thread.start()
59+
60+
def listen_loop(self):
5461
"""
5562
Creates and binds sockets using TCP variables then listens for incoming connections.
5663
For each new connection a client thread will be created to handle communication.
@@ -59,19 +66,15 @@ def start(self):
5966
tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
6067
tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
6168
tcp_server.bind((self.tcp_ip, self.tcp_port))
62-
threads = []
6369

6470
while True:
6571
tcp_server.listen(self.connections)
6672

67-
(conn, (ip, port)) = tcp_server.accept()
68-
new_thread = ClientThread(conn, self, ip, port)
69-
new_thread.start()
70-
threads.append(new_thread)
71-
72-
# Unreachable statements:
73-
# for t in threads:
74-
# t.join()
73+
try:
74+
(conn, (ip, port)) = tcp_server.accept()
75+
ClientThread(conn, self, ip, port).start()
76+
except socket.timeout as err:
77+
logging.exception("ros_tcp_endpoint.TcpServer: socket timeout")
7578

7679
def send_unity_error(self, error):
7780
self.unity_tcp_sender.send_unity_error(error)

0 commit comments

Comments
 (0)