WSAEventSelect with FD_ACCEPT, recv returns WSAEWOULDBLOCK
I'm trying to setup a socket that won't block on accept(...), using the following code:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("127.0.0.1", 1234))
event = win32event.CreateEvent(None, True, False, None)
win32file.WSAEventSelect(sock.fileno(), event, win32file.FD_ACCEPT)
sock.listen(5)
rc = win32event.WaitForSingleObject(event, win32event.INFINITE)
if not rc == win32event.WAIT_OBJECT_0:
return
conn, addr = sock.accept()
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
When a client connects but there's no data, recv
returns WSAEWOULDBLOCK
. Reading MSDN explains this is the right behavior for non-blocking sockets but when using WSAEventSelect
I only specified FD_ACCEPT
, without FD_READ
. Therefore I expe开发者_如何学Pythonct recv
to block when there's no data, and to return with 0 when the connection was gracefully closed.
What am I doing wrong?
Solved this by: adding the following lines before accept
:
win32file.WSAEventSelect(sock.fileno(), event, 0)
sock.setblocking(1)
精彩评论