Reading data from a python socket received from multiple clients -
i writing python program (master.py) read data received 2 separate clients. code example:
master.py:
data_agg = '' host = '172.31.31.207' port = 50008 s = socket.socket(socket.af_inet, socket.sock_stream) s.bind((host, port)) s.listen(2) conn, addr = s.accept() print 'connected by', addr while 1: data = conn.recv(65535) data_agg += data if not data: break data_arr = json.loads(data_agg.decode('utf-8')) data_arr = sorted(data_arr) print "sorted attay: \n" print data_arr
two clients have following code:
host = '172.31.31.207' port = 50008 s0 = socket.socket(socket.af_inet, socket.sock_stream) s0.connect((host, port)) s0.send(sorted_data_string) s0.close()
however receive data single client. proper way read data socket arriving multiple receivers?
i modified code bit , can handle 2 or more clients.
, suggest calling accept
on main thread , , recv
on seperate thread task
data_agg = [] host = '172.31.31.207' port = 50008 s = socket.socket(socket.af_inet, socket.sock_stream) s.bind((host, port)) s.listen(2) in range(2) : ## can change number accept more clients conn, addr = s.accept() print 'connected by', addr data_received = '' while 1: data = conn.recv(65535) if not data or len(data) == 0 : break data_received += data data_agg += [ data_received ] conn.close() s.close() d in data_agg : data_arr = json.loads(d.decode('utf-8')) data_arr = sorted(data_arr) print "sorted attay: \n" print data_arr
you improve above code using thread
, can handle multiple clients simultaneously .
can defining handle_client
function , , run on new thread .
while true : conn, addr = s.accept() print 'connected by', addr start_new_thread(handle_client, (conn,))
Comments
Post a Comment