[英]non-blocking socket,error is always
sock.setblocking(0)
try:
data = sock.recv(1024)
except socket.error, e:
if e.args[0] == errno.EWOULDBLOCK:
print 'EWOULDBLOCK'
else:
if not data: #recv over
sock.close()
print 'close================='
else:
print 'recv ---data---------'
poem += data
all above code is in a loop.using non-blocking socket
(just want to test 'non-blocking socket') to get data. 所有上面的代码都在循环中。
non-blocking socket
(只是想测试'非阻塞套接字')来获取数据。 But always print 'EWOULDBLOCK',i don't know why? 但总是打印'EWOULDBLOCK',我不知道为什么?
The socket is non-blocking so recv()
will raise an exception if there is no data to read. 套接字是非阻塞的,因此如果没有要读取的数据,
recv()
将引发异常。 Note that errno.EWOULDBLOCK = errno.EAGAIN = 11. This is Python's (well the OS really) way of telling you to try the recv()
again later. 请注意,errno.EWOULDBLOCK = errno.EAGAIN = 11.这是Python(实际上是操作系统)告诉您稍后再次尝试
recv()
。
I note that you close the socket each time you get this exception. 我注意到每次出现此异常时都会关闭套接字。 That's not going to help at all.
这根本没有帮助。 Your code should be something like this:
你的代码应该是这样的:
import socket, errno, time
sock = socket.socket()
sock.connect(('hostname', 1234))
sock.setblocking(0)
while True:
try:
data = sock.recv(1024)
if not data:
print "connection closed"
sock.close()
break
else:
print "Received %d bytes: '%s'" % (len(data), data)
except socket.error, e:
if e.args[0] == errno.EWOULDBLOCK:
print 'EWOULDBLOCK'
time.sleep(1) # short delay, no tight loops
else:
print e
break
For this sort of thing, the select
module is usually the way to go. 对于这种事情,
select
模块通常是要走的路。
The exception is raised by design, cause you are using non-blocking IO
. 设计会引发异常,因为您使用
non-blocking IO
。
The major mechanical difference is that send, recv, connect and accept can return without having done anything.
主要的机械差异是send,recv,connect和accept可以在没有做任何事情的情况下返回。 You have (of course) a number of choices.
你(当然)有很多选择。 You can check return code and error codes and generally drive yourself crazy.
您可以检查返回代码和错误代码,通常会让自己发疯。
Quoted from Python doc 引自Python doc
If you run man errno 3
, you shall see the description of EWOULDBLOCK
. 如果你运行
man errno 3
,你将看到EWOULDBLOCK
的描述。 The exception is reasonable, because there is no data to read yet. 这个例外是合理的,因为还没有数据可供阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.