views:

92

answers:

2

i'm reading some code and i've come across this line

socket.error errno.EWOULDBLOCK

can anyone tell me what the conditions have to be to raise this error?

+2  A: 

From Python's socket module: http://docs.python.org/library/socket.html

Initially all sockets are in blocking mode. In non-blocking mode, if a recv() call doesn’t find any data, or if a send() call can’t immediately dispose of the data, a error exception is raised.

The error exception it's referring to is errno.EWOULDBLOCK

For this to happen, the socket object must be set to non-blocking mode using: socketObj.setblocking(0)

Coding District
+1  A: 

Note that EWOULDBLOCK is error number 11:

In [80]: import errno
In [83]: errno.EWOULDBLOCK
Out[84]: 11

And the associated error message is:

In [86]: import os
In [87]: os.strerror(errno.EWOULDBLOCK)
Out[89]: 'Resource temporarily unavailable'

Here is some toy code which exhibits the EWOULDBLOCK error. It sets up a server and client which try to talk to each other over a socket connection. When s.setblocking(0) is called to put the socket in non-blocking mode, a subsequent call to s.recv raises the socket.error. I think this happens because both ends of the connection are trying to receive data:

import socket
import multiprocessing as mp
import sys
import time

def server():
    HOST='localhost'
    PORT=6000
    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr=s.accept()
    while True:
        data=conn.recv(1024)
        if data:
            conn.send(data)
    conn.close()   
def client():
    HOST='localhost'
    PORT=6000
    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    s.setblocking(0)     # Comment this out, and the EWOULDBLOCK error goes away
    s.send('Hello, world')
    try:
        data=s.recv(1024)
    except socket.error as err:
        print(err)
        # [Errno 11] Resource temporarily unavailable
        sys.exit()
    finally:
        s.close()
    print('Received {0}'.format(repr(data)))
def run():
    server_process=mp.Process(target=server)
    server_process.daemon=True
    server_process.start()
    time.sleep(0.1)
    client()   
run()

If s.setblocking(0) is commented-out, you should see

Received 'Hello, world'
unutbu