python socket.recv/sendall 调用阻塞

发布于 2024-08-27 08:26:13 字数 728 浏览 10 评论 0原文

这篇文章被错误地标记为“发送”,因为我无法创建新标签。

我对这个简单的回显服务器有一个非常基本的问题。这是一些代码片段。

客户端

while True:
 data = raw_input("Enter data: ")
 mySock.sendall(data)
 echoedData = mySock.recv(1024)
 if not echoedData: break
 print echoedData

服务器

while True:
 print "Waiting for connection"
 (clientSock, address) = serverSock.accept()
 print "Entering read loop"
 while True:
     print "Waiting for data"
     data = clientSock.recv(1024)
     if not data: break
     clientSock.send(data)
 clientSock.close()

现在这工作正常,除非客户端发送一个空字符串(通过按返回键响应“输入数据:”),在这种情况下我看到一些死锁行为。

现在,当用户在客户端按下回车键时到底会发生什么?我只能想象,sendall调用会阻塞等待一些数据添加到发送缓冲区,从而导致recv调用依次阻塞。这是怎么回事?

感谢您的阅读!

This post is incorrectly tagged 'send' since I cannot create new tags.

I have a very basic question about this simple echo server. Here are some code snippets.

client

while True:
 data = raw_input("Enter data: ")
 mySock.sendall(data)
 echoedData = mySock.recv(1024)
 if not echoedData: break
 print echoedData

server

while True:
 print "Waiting for connection"
 (clientSock, address) = serverSock.accept()
 print "Entering read loop"
 while True:
     print "Waiting for data"
     data = clientSock.recv(1024)
     if not data: break
     clientSock.send(data)
 clientSock.close()

Now this works alright, except when the client sends an empty string (by hitting the return key in response to "enter data: "), in which case I see some deadlock-ish behavior.

Now, what exactly happens when the user presses return on the client side? I can only imagine that the sendall call blocks waiting for some data to be added to the send buffer, causing the recv call to block in turn. What's going on here?

Thanks for reading!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

累赘 2024-09-03 08:26:13

更像是,sendall() 调用不执行任何操作(因为没有数据要发送),因此 recv() 调用客户端阻塞等待数据,但由于没有向服务器发送任何数据,服务器永远不会发回任何数据,因为它在其初始 recv() 上也被阻塞,因此两个进程都被阻塞。

More like, the sendall() call does nothing (since there's no data to send), and thus the recv() call on the client blocks waiting for data, but since nothing was sent to the server, the server never sends any data back since it's also blocked on its initial recv(), and thus both processes are blocked.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文