通过UDP发送列表

时间:2018-12-08 14:15:28

标签: python sockets udp python-2.x

我正在使用套接字编程来发送UDP文本消息,并且工作正常。这是代码:

发送:

import socket
UDP_IP = "10.0.0.2"
UDP_PORT = 5005
MESSAGE = "Hello"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

接收:

import socket

UDP_IP = "10.0.0.2"
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
  data, addr = sock.recvfrom(1024)
  print "received message:", data

现在,我想更改要发送到列表的消息。我尝试使用pickle来做到这一点。这是代码:

发送:

import socket
import pickle

UDP_IP = "10.0.0.2"
UDP_PORT = 5005
a = []
a.append('H')
a.append('G')
MESSAGE = pickle.dumps(a)
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

接收:

import socket
import pickle

UDP_IP = "10.0.0.2"
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
  data, addr = sock.recvfrom(1024)
  print "received message:", data
  pickle.loads(data)
  print(data)

但是我在接收方没有得到正确的列表形式。输出如下:

(1p0
S'H'
p1
aS'G'
p2
a.

(1p0
S'H'
p1
aS'G'
p2
a.

怎么了?

2 个答案:

答案 0 :(得分:1)

问题已解决。该代码运行正常,出现了一个问题,因为我正在打印数据本身而不是pickle.loads(data)的输出,因此该代码现在运行良好:

接收:

import socket
import pickle

UDP_IP = "10.0.0.2"
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
  data, addr = sock.recvfrom(1024)
  print "received message:", data
  print(pickle.loads(data))

答案 1 :(得分:0)

套接字对字节(二进制数据)进行操作。
将数据发送到套接字连接(str.encode())时对字符串进行编码
并使用bytes.decode('utf8')解码从套接字接收的字节序列。

https://docs.python.org/3/howto/sockets.html#socket-howto