socket.recv(recv_size) 什么时候返回? [英] When does socket.recv(recv_size) return?

查看:26
本文介绍了socket.recv(recv_size) 什么时候返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过测试,我得出结论,在以下三种情况下 socket.recv(recv_size) 将返回.

From test, I concluded that in following three cases the socket.recv(recv_size) will return.

  1. 连接关闭后.例如,客户端调用 socket.close() 或发生任何套接字错误,它将返回空字符串.

  1. After the connection was closed. For example, the client side called socket.close() or any socket error occurred, it would return empty string.

一些数据来了,数据的大小超过了recv_size.

Some data come, the size of data is more than recv_size.

有关#3 的更多详细信息:

More details about #3:

#server.py

while True:
    data = sock.recv(10)
    print data, 'EOF'

#client1.py

sock.sendall("12345")
sock.sendall("a" * 50)

#client2.py

sock.sendall("12345")
time.sleep(0.1)
sock.sendall("a" * 50)

当我运行 client1.py 时,server.py 回显:

When I run client1.py, the server.py echos:

12345aaaaa EOF
aaaaaaaaaa EOF
aaaaaaaaaa EOF
aaaaaaaaaa EOF
aaaaaaaaaa EOF
aaaaa EOF

当我运行 client2.py 时,server.py 回显:

When I run client2.py, the server.py echos:

12345 EOF
aaaaaaaaaa EOF
aaaaaaaaaa EOF
aaaaaaaaaa EOF
aaaaaaaaaa EOF
aaaaaaaaaa EOF

我的结论正确吗?哪里可以看到关于#3的官方说明?

Are my conclusions correct? Where can I see the official description about #3?

推荐答案

是的,你的结论是正确的.socket.recv 是一个阻塞调用.

Yes, your conclusion is correct. socket.recv is a blocking call.

socket.recv(1024) 最多读取 1024 个字节,如果没有数据等待读取则阻塞.如果您没有读取所有数据,则不会阻止对 socket.recv 的其他调用.

socket.recv(1024) will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv won't block.

socket.recv 也会以空字符串结尾.

socket.recv will also end with an empty string if the connection is closed or there is an error.

如果你想要一个非阻塞的socket,你可以使用select模块(比只使用socket复杂一点)或者你可以使用socket.setblocking.

If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking.

我过去在使用 socket.setblocking 时遇到过问题,但如果您愿意,可以随时尝试.

I had issues with socket.setblocking in the past, but feel free to try it if you want.

这篇关于socket.recv(recv_size) 什么时候返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆