如何接收和处理多个 TCP 流套接字?

我想使用套接字模块通过 TCP 将移动点的位置发送到服务器。该点位置在循环的每次迭代中更新,并以已使用 pickle方法序列化for的元组的形式发送。(x, y)dumps

问题:

在服务器端,似乎我只能从该循环的第一次迭代中接收位置。好像在此过程中跳过或丢失了所有以下更新的位置。

我不能确定这种行为背后的原因是什么,但我敢打赌我没有在服务器端正确设置东西。我怀疑由于我可能在使用套接字模块时犯了一些错误(我对网络接口的世界是全新的),数据将被完全发送但在接收时没有得到充分处理。


Cats萌萌
浏览 108回答 1
1回答

喵喔喔

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

相关分类

Python