python socket.recv/sendall 调用阻塞
这篇文章被错误地标记为“发送”,因为我无法创建新标签。
我对这个简单的回显服务器有一个非常基本的问题。这是一些代码片段。
客户端
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更像是,
sendall()
调用不执行任何操作(因为没有数据要发送),因此recv()
调用客户端阻塞等待数据,但由于没有向服务器发送任何数据,服务器永远不会发回任何数据,因为它在其初始recv()
上也被阻塞,因此两个进程都被阻塞。More like, the
sendall()
call does nothing (since there's no data to send), and thus therecv()
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 initialrecv()
, and thus both processes are blocked.