我使用的是 python 2.7,我必须使用 udp 中的套接字编程在两个主机之间发送一个方阵。我的代码发送一个字符串,但不发送矩阵。
这是我的代码:
import socket
import thread
import time
import ctypes
matrix = [[1,2],[3,5]]
def c():
#print (file.read())
UDP_IP = "127.0.0.1"
UDP_PORT = 5002
#MESSAGE = "Hello, World!"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
#print ("message:", MESSAGE)
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(matrix, (UDP_IP, UDP_PORT))
def s():
UDP_IP = "127.0.0.1"
UDP_PORT = 5002
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
while True:
thread.start_new_thread(c, ())
thread.start_new_thread(s, ())
time.sleep(10)
另外,我在网上找到了这段代码。它发送一个矩阵,但我无法根据我的需要对其进行反序列化(以矩阵形式作为输入)。如果有人能帮助我理解这一点,那将会有很大帮助。
服务器端:
import socket, pickle
HOST = "127.0.0.1"
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()
客户端
import socket, pickle
HOST = "127.0.0.1"
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
arr = [[11111],[1,2,3,4],[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)
首先,您应该在发送数据时从同一端口读取数据。数据必须以二进制形式发送。您可以像第二个示例一样使用 pickle
。不要一遍又一遍地启动服务器线程。
import socket
import time
import pickle
import threading
UDP_IP = "127.0.0.1"
UDP_PORT = 5002
def server():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(102400)
matrix = pickle.loads(data)
print "received message:", matrix
def send_matrix(matrix):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = pickle.dumps(matrix)
sock.sendto(data, (UDP_IP, UDP_PORT))
threading.Thread(target=server).start()
matrix = [[1,2],[3,5]]
while True:
send_matrix(matrix)
time.sleep(10)
我是一名优秀的程序员,十分优秀!