当客户端需要数据时,Python 套接字在 socket.recv() 上保持阻塞状态

标签 python sockets network-programming client-server

我正在尝试使用 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/

相关文章:

python - ryu 在将流添加到交换机后使用交换机处理数据包

python - 从数据库中检索更新的表 - MySQLdb

python - 遍历 pandas 数据框中的所有列以按分隔符拆分

c++ - boost asio 服务器在关闭 boost::socket 的调用中挂起

java - 套接字:为什么我来自服务器的消息总是被分成完全相同的 2 条消息?

c - pcap_loop 只是等待

c - sethostname 标识符未找到错误

Python - SQLite JSON1 加载扩展

python - 如何调试 fastcgi 应用程序?

c++ - Boost::asio udp socket - 我应该如何使用 API 来允许取消读取?