import socket import threading import time import random import fcntl,os # this function a client that waits for 1 second and then says "hi" def openconnection(): c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) c.connect(addr) time.sleep(1) c.send('hi') # listen for connections addr = ('127.0.0.1',random.randint(1025,65531)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(addr) s.listen(5) # This timeout is the key. Even though it is much longer than the code will # execute, removing it will fix the problem. s.settimeout(10) # start the client in 1 second... t1 = threading.Timer(1, openconnection) t1.start() # get a connection (a,host) = s.accept() # Python thinks that a is a blocking socket. On Mac / BSD, the OS disagrees print 'a has timeout:',a.gettimeout() print 'O_NONBLOCK is set:',(fcntl.fcntl(a.fileno(), fcntl.F_GETFL)&os.O_NONBLOCK) !=0 # do a send in .1 second (give the recv below a chance to run) t2 = threading.Timer(.1, a.send,args=("hello",)) t2.start() message = a.recv(1024) print 'received:',message a.close()