Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-Blocking error when adding timeout to python server

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.

like image 630
Richard Avatar asked Oct 24 '13 15:10

Richard


1 Answers

You can turn on blocking:

    # ...
    conn.setblocking(1)
    return conn
# ...
like image 141
User Avatar answered Oct 21 '22 22:10

User