我正在尝试使用 Python 进行套接字编程,但遇到了一个问题。 “服务器”端的代码是:
(connection, address) = in_socket.accept()
size_str = connection.recv(4)
result_size=struct.unpack('>i',size_str)
string_buffer=[]
print 'results size is: ',result_size[0]
while 1:
r = connection.recv(result_size[0])
print 'length is: ', len(r)
if not r:
break
string_buffer.append(r)
s = ''.join(string_buffer)
print 'recieved data: ', s
connection.send('Thanks for connecting')
对于客户端,它是:
sock.connect(server_address)
message = ('{\"message\":\"This is the messcxvage\"}')
packedlen=struct.pack('>i',len(message))
sock.send(packedlen)
sock.send(message)
xyz = sock.recv(1024)
当客户端期待返回数据时,服务器中用于跳出 while 循环的 if 条件永远不会满足。服务器一直在等待接收更多数据。如果我注释掉两个代码示例的最后几行,它会按预期工作。为什么会发生这种情况,解决方法是什么?
提前致谢!
最佳答案
Why does this happen
您在评论中正确回答了这个问题。
and what is the fix for this?
只是不要编写无限循环。您明智地将数据长度从客户端发送到服务器,因此服务器知道要等待多少字节。在 UNIX 系统上,处理整个 while 1:
循环以及 s = ''.join(string_buffer)
和 write only
s = connection.recv(result_size[0], socket.MSG_WAITALL)
相反。在 Windows 系统(没有 MSG_WAITALL)上,您仍然需要循环,但仅在收到 result_size[0]
个字节之前。
关于当客户端需要数据时,Python 套接字在 socket.recv() 上保持阻塞状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30773609/