import socket from select import select from collections import deque
tasks = deque() r_wait = {} s_wait = {}
def fib(n): if n <= 2: return 1 return fib(n-1)+fib(n-2)
def run(): while any([tasks,r_wait,s_wait]): while not tasks:
rr, sr, _ = select(r_wait, s_wait, {}) for _ in rr: tasks.append(r_wait.pop(_)) for _ in sr: tasks.append(s_wait.pop(_)) try: task = tasks.popleft() why,what = task.next() if why == 'recv': r_wait[what] = task elif why == 'send': s_wait[what] = task else: raise RuntimeError except StopIteration: pass
def fib_server(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1) sock.bind(('localhost',5566)) sock.listen(5) while True: yield 'recv', sock c, a = sock.accept() tasks.append(fib_handler(c))
def fib_handler(client): while True: yield 'recv', client req = client.recv(1024) if not req: break resp = fib(int(req)) yield 'send', client client.send(str(resp)+'\n') client.close()
tasks.append(fib_server()) run()
output: (bash 1)
$ nc loalhost 5566 20 6765
output: (bash 2)
$ nc localhost 5566 10 55
|