Passing _socketobjects as parameters

I am writing a multi-threaded distributed network algorithm.

I have one thread that listens for new connections. Each time a new connection is established, a separate stream is launched to listen to messages from this connection.

My problem is that the socket I open works fine in both directions inside the connection listener. After I pass the socket object for this connection to the message listener, I can read data from the socket, but sending data through it does not reach the remote host.

Here is the main snip from my code:

def connection_listener(port, start_e, terminate_e): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.settimeout(1) s.bind(('', port)) s.listen(1) while (not start_e.isSet()): try: conn, addr = s.accept() msg_in = conn.recv(1024).split(":") if (msg_in[1]=="hello"): # If addr sends us a 'id:hello', we reply with a 'my_id:welcome' conn.send(str(my_id)+":welcome") t = Thread(target=message_listener, args=(conn, addr[0], terminate_e, )) t.start() except: pass # timeout def message_listener(conn, address, terminate_e): while (not terminate_e.isSet()): try: msg_in = conn.recv(1024) # Here I can receive everything that I send from the other end of conn, # but conn.send("any data") doesn't reach the remote host 

What I would like to do is send messages like confirmation from the message listener thread using conn. Is this possible somehow or am I thinking and doing it wrong?

+4
source share
1 answer

I figured it out myself, so I will share my answer.

I made messages about changing the fixed size of the protocol by traversing with zeros to the desired length. I used a length of 32 bytes, which can be quite small in terms of hardware. However, it seems to work as intended.

Pragmatically, my solution looks like this:

 def send_everyone(message): for i in range(len(peers)): chunk = (str(my_id)+":"+message).rjust(32, '0') peers[i].send(chunk) 

And on the receiving side, we want only 32 bytes at a time:

 def message_listener(conn, address, terminate_e): while (not terminate_e.isSet()): try: msg_in = conn.recv(32) ... 
+1
source

Source: https://habr.com/ru/post/1393640/


All Articles