如何通过python中的套接字发送数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24423162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to send an array over a socket in python
提问by user3774358
I have an array kind of ([1,2,3,4,5,6],[1,2,3,4,5,6])
this. I have to send it over a STREAM/TCP socket in python. Then I have to receive the same array at the receiving end.
我有一个这样的数组([1,2,3,4,5,6],[1,2,3,4,5,6])
。我必须通过 python 中的 STREAM/TCP 套接字发送它。然后我必须在接收端接收相同的数组。
采纳答案by hashbrown
回答by danielpopa
Sockets are byte streams, so ideal is to write your protocol (read this)
套接字是字节流,因此理想的是编写您的协议(阅读本文)
This is a basic example without protocol and you should care about buffer -> recv(). If it is too small, your data will be chopped off. That's why you should implement a protocol, if you send unknown size of data.
这是一个没有协议的基本示例,您应该关心缓冲区 -> recv()。如果它太小,您的数据将被砍掉。这就是为什么你应该实现一个协议,如果你发送未知大小的数据。
Client:
客户:
import socket, pickle
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
arr = ([1,2,3,4,5,6],[1,2,3,4,5,6])
data_string = pickle.dumps(arr)
s.send(data_string)
data = s.recv(4096)
data_arr = pickle.loads(data)
s.close()
print 'Received', repr(data_arr)
Server:
服务器:
import socket
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(4096)
if not data: break
conn.send(data)
conn.close()
回答by Leo103
I solved this problem using json (since I heard pickle is unsafe)
我使用 json 解决了这个问题(因为我听说泡菜不安全)
client:
客户:
import json
...
arr1 = [1,2,3]
arr2 = [4,5,6]
someVar = 7
data = json.dumps({"a": arr1, "b": arr2, "c": someVar})
socket.send(data.encode())
server:
服务器:
import json
...
data = socket.recv(1024)
data = json.loads(data.decode())
arr = data.get("a")
var = data.get("c")
Here we deserialize the json string, using data.get("a")
which you can interpret as data.a
这里我们反序列化 json 字符串,data.get("a")
您可以使用它来解释为data.a