import socket import threading to_send = 1024 * 1024 def listen_and_receive(): s = socket.socket() s.bind(('localhost', 27017)) s.listen(1) conn, addr = s.accept() while True: data = conn.recv(1024) if not data: break conn.close() t = threading.Thread(target=listen_and_receive) t.start() c = socket.socket() c.connect(('localhost', 27017)) # sendall from cpython returns None or raises sent = c.sendall("x" * to_send) c.close() t.join(10) assert to_send == sent, "should have sent %d, only sent %d" % (to_send, sent)