简体   繁体   English

如何通过 TCP 套接字发送列表 - Python

[英]How to send a list through TCP sockets - Python

I want to send a list through TCP sockets but i can't get the exact list when receiving from the server-side .我想通过 TCP 套接字发送一个列表,但是从服务器端接收时我无法获得确切的列表。 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]数据=[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 ?任何想法我的代码出了什么问题?

Use pickle or json to send list(or any other object for that matter) over sockets depending on the receiving side.根据接收方的不同,使用picklejson通过套接字发送列表(或任何其他对象)。 You don't need json in this case as your receiving host is using python.在这种情况下,您不需要json ,因为您的接收主机正在使用 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.在接收端使用pickle.loads(recvd_data)

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

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() .然后,接收端可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM