如何通过TCP套接字发送列表-Python [英] How to send a list through TCP sockets - Python

查看:577
本文介绍了如何通过TCP套接字发送列表-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过TCP套接字发送一个列表,但是从服务器端接收时我无法获得确切的列表. 更具体地说,我有这个列表:

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]

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 ?

推荐答案

根据接收方的不同,使用picklejson通过套接字发送列表(或其他任何对象).在这种情况下,您不需要json,因为您的接收主机正在使用python.

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)

在接收方使用pickle.loads(recvd_data).

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

这篇关于如何通过TCP套接字发送列表-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆