16
16
import socket
17
17
import json
18
18
import sys
19
+ import threading
19
20
20
21
from .tcp_sender import UnityTcpSender
21
22
from .client import ClientThread
@@ -51,6 +52,12 @@ def __init__(self, node_name, buffer_size=1024, connections=10):
51
52
self .syscommands = SysCommands (self )
52
53
53
54
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 ):
54
61
"""
55
62
Creates and binds sockets using TCP variables then listens for incoming connections.
56
63
For each new connection a client thread will be created to handle communication.
@@ -59,19 +66,15 @@ def start(self):
59
66
tcp_server = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
60
67
tcp_server .setsockopt (socket .SOL_SOCKET , socket .SO_REUSEADDR , 1 )
61
68
tcp_server .bind ((self .tcp_ip , self .tcp_port ))
62
- threads = []
63
69
64
70
while True :
65
71
tcp_server .listen (self .connections )
66
72
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" )
75
78
76
79
def send_unity_error (self , error ):
77
80
self .unity_tcp_sender .send_unity_error (error )
0 commit comments