Non-Blocking error when adding timeout to python server

Richard picture Richard · Oct 24, 2013 · Viewed 12.3k times · Source

I am writing a simple TCP server in python, and am trying to input a timeout. My current code:

import socket


def connect():
    HOST = ''                 # Symbolic name meaning the local host
    PORT = 5007             # Arbitrary non-privileged port
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(1)
    s.settimeout(5)
    conn, addr = s.accept()
    print 'Connected by', addr
    return conn

conn = connect()

while 1:
    data = conn.recv(1024)
    if not data: break
    print data
conn.close()

Issue is when I try to connect I get an error at data = conn.recv(1024)

error: [Errno 10035] A non-blocking socket operation could not be completed immediately

Code works without the timeout.

Answer

User picture User · Oct 24, 2013

You can turn on blocking:

    # ...
    conn.setblocking(1)
    return conn
# ...