How to send a list through TCP sockets – Python

Question:

I want to send a list through TCP sockets but i can’t get the exact list when receiving from the server-side .
To be more specific say that i have this list:

 y=[0,12,6,8,3,2,10] 

Then, i send each item of the list like this:

 for x in y :
 s.send(str(x))

Now the code of server to recieve the data looks like this:

 while True:
 data = connection.recv(4096)
 if data:
 print('received "%s"' % data)             
 else:
 print('no more data from', client_address)
 break

The problem is that when i run the program i don’t get the same list but something like this:

data=[012,6,83,210]

Also, everytime i run the program i get a different result for list data

Any ideas what’s going wrong with my code ?

Asked By: Moras

||

Answers:

Use pickle or json to send list(or any other object for that matter) over sockets depending on the receiving side. You don’t need json in this case as your receiving host is using python.

import pickle
y=[0,12,6,8,3,2,10] 
data=pickle.dumps(y)
s.send(data)

Use pickle.loads(recvd_data) on the receiving side.

Reference: https://docs.python.org/2/library/pickle.html

Answered By: shiva

Sorry for my extremely late response, but I hope this can help anyone else who has this problem. This may not be the best solution, but I would convert the list into a string, and encode and send that string. Then, the receiving end can receive, decode, and convert this string back into a list using eval(). This would look something like this:

Sender:

y = [0,12,6,8,3,2,10] 
# Convert To String
y = str(y)
# Encode String
y = y.encode()
# Send Encoded String version of the List
s.send(y)

Receiver:

data = connection.recv(4096)
# Decode received data into UTF-8
data = data.decode('utf-8')
# Convert decoded data into list
data = eval(data)
Answered By: SomeMosa
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.