The problem is with a simple example of a socket server with the processing of each incoming connection in a separate thread (thread). It seems that the stream created for processing a new connection blocks the execution of the main stream. There is a server code:
import socket import threading def worker(conn, addr): with conn: while True: print("wait recv from", addr) data = conn.recv(1024) print("recv", data) if not data: break with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.bind(("", 7001)) sock.listen(socket.SOMAXCONN) while True: print("wait accept...") conn, addr = sock.accept() print("accept new connection from", addr) th = threading.Thread(target=worker, args=(conn, addr)) th.start() th.join() I launch two socket clients. In two consoles I type the code in the python interpreter:
import socket s = socket.create_connection(("", 7001)) s.send(b"ping") The connection remains hanging open. At the same time in the server console I see messages about only one connection. But when I close it by running the code
s.close() Then there are messages about the second client. It seems that the line data = conn.recv (1024) blocks not only its own stream, but also the main one, in which a new connection should be expected.
Actually the question is: is there a mistake in the code or is it a normal correct behavior?
th.join()clean. - Sergey Gornostaev