<s> import select <EOL> import socket <EOL> import sys <EOL> import Queue <EOL> server = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) <EOL> server . setblocking ( <NUM_LIT:0> ) <EOL> server_address = ( '<STR_LIT:localhost>' , <NUM_LIT> ) <EOL> print >> sys . stderr , '<STR_LIT>' % server_address <EOL> server . bind ( server_address ) <EOL> server . listen ( <NUM_LIT:5> ) <EOL> message_queues = { } <EOL> TIMEOUT = <NUM_LIT:1000> <EOL> READ_ONLY = select . POLLIN | select . POLLPRI | select . POLLHUP <EOL> READ_WRITE = READ_ONLY | select . POLLOUT <EOL> poller = select . poll ( ) <EOL> poller . register ( server , READ_ONLY ) <EOL> fd_to_socket = { server . fileno ( ) : server , } <EOL> while True : <EOL> print >> sys . stderr , '<STR_LIT>' <EOL> events = poller . poll ( TIMEOUT ) <EOL> for fd , flag in events : <EOL> s = fd_to_socket [ fd ] <EOL> if flag & ( select . POLLIN | select . POLLPRI ) : <EOL> if s is server : <EOL> connection , client_address = s . accept ( ) <EOL> print >> sys . stderr , '<STR_LIT>' , client_address <EOL> connection . setblocking ( <NUM_LIT:0> ) <EOL> fd_to_socket [ connection . fileno ( ) ] = connection <EOL> poller . register ( connection , READ_ONLY ) <EOL> message_queues [ connection ] = Queue . Queue ( ) <EOL> else : <EOL> data = s . recv ( <NUM_LIT> ) <EOL> if data : <EOL> print >> sys . stderr , '<STR_LIT>' % ( data , s . getpeername ( ) ) <EOL> message_queues [ s ] . put ( data ) <EOL> poller . modify ( s , READ_WRITE ) <EOL> else : <EOL> print >> sys . stderr , '<STR_LIT>' , client_address , '<STR_LIT>' <EOL> poller . unregister ( s ) <EOL> s . close ( ) <EOL> del message_queues [ s ] <EOL> elif flag & select . POLLHUP : <EOL> print >> sys . stderr , '<STR_LIT>' , client_address , '<STR_LIT>' <EOL> poller . unregister ( s ) <EOL> s . close ( ) <EOL> elif flag & select . POLLOUT : <EOL> try : <EOL> next_msg = message_queues [ s ] . get_nowait ( ) <EOL> except Queue . Empty : <EOL> print >> sys . stderr , '<STR_LIT>' , s . getpeername ( ) , '<STR_LIT>' <EOL> poller . modify ( s , READ_ONLY ) <EOL> else : <EOL> print >> sys . stderr , '<STR_LIT>' % ( next_msg , s . getpeername ( ) ) <EOL> s . send ( next_msg ) <EOL> elif flag & select . POLLERR : <EOL> print >> sys . stderr , '<STR_LIT>' , s . getpeername ( ) <EOL> poller . unregister ( s ) <EOL> s . close ( ) <EOL> del message_queues [ s ] </s>
