Here's a working example server application which has Socket.accept()
outside the loop:
class (threading.Thread):
def listenForClients(self, sock):
while True:
client, address = sock.accept()
client.settimeout(5)
threading.Thread( target = self.listenToClient, args = (client,address) ).start()
def listenToClient(self, client, address):
size = 1024
while True:
try:
data = client.recv(size)
if data:
response = "Got connection"
client.send(response)
else:
raise error('Client disconnected')
except:
client.close()
return False
def __init__(self, host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(5)
self.listenForClients(sock)
this uses a thread for each client because otherwise Socket.recv()
blocks so clients would have to take turns.