import select
import socket
import sys
import Queue
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
server_addr = ('localhost', 10000)
print('starting server on {server_addr[0]}:{server_addr[1]}')
server.bind(server_address)
server.listen(5)
inputs = [ server ]
outputs = [ ]
message_queues = {}
while inputs:
print('waiting for the next event')
readable, writable, exceptional = select.select(inputs, outputs, inputs)
for s in readable:
if s is server:
connection, client_address = s.accept()
print(f'new connection from {client_address}')
connection.setblocking(False)
inputs.append(connection)
message_queues[connection] = Queue.Queue()
else:
data = s.recv(1024)
if data:
print(f'received "{data}" from {s.getpeername()}')
message_queues[s].put(data)
if s not in outputs:
outputs.append(s)
else:
print(f'closing {client_address} after reading no data')
if s in outputs:
outputs.remove(s)
inputs.remove(s)
s.close()
del message_queues[s]
for s in writable:
try:
next_msg = message_queues[s].get_nowait()
except Queue.Empty:
print(f'output queue for {s.getpeername()} is empty')
outputs.remove(s)
else:
print(f'sending "{next_msg}" to {s.getpeername()}')
s.send(next_msg)
for s in exceptional:
print(f'handling exceptional condition for {s.getpeername()}')
inputs.remove(s)
if s in outputs:
outputs.remove(s)
s.close()
del message_queues[s]