1 回答
TA贡献1735条经验 获得超5个赞
您需要将 connection, address = s.accept() 放在 while 循环之外,否则您的服务器每次都会等待新连接。
您接收数据的方式也有问题。connection.recv(4096)并非每次收到完整的“数据”消息时都会返回 0 到 4096 之间的任意字节数。要处理此问题,您可以在向您发送 json 之前发送一个标头,指示应接收多少数据通过添加标头,您将确保正确接收您发送的数据消息。
此示例中的标头是一个四字节的 int,指示数据的大小。
服务器
import pickle
import socket
import struct
HEADER_SIZE = 4
HOST = "127.0.0.1"
PORT = 12000
def receive(nb_bytes, conn):
# Ensure that exactly the desired amount of bytes is received
received = bytearray()
while len(received) < nb_bytes:
received += conn.recv(nb_bytes - len(received))
return received
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
connection, address = s.accept()
while True:
# receive header
header = receive(HEADER_SIZE, connection)
data_size = struct.unpack(">i", header)[0]
# receive data
data = receive(data_size, connection)
print(pickle.loads(data))
客户
import socket
import pickle
import math
HEADER_SIZE = 4
HOST = "127.0.0.1"
PORT = 12000
den = 20
rad = 100
theta = math.tau / den
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, PORT)) #connect to server
for step in range(1000):
i = step%den
x = math.cos(i*theta) * rad
y = math.sin(i*theta) * rad
data = pickle.dumps((x, y), protocol=0)
# compute header by taking the byte representation of the int
header = len(data).to_bytes(HEADER_SIZE, byteorder ='big')
sock.sendall(header + data)
希望能帮助到你
添加回答
举报