#!/usr/bin/env python # Foundations of Python Network Programming - Chapter 7 - server_simple.py # Simple server that only serves one client at a time; others have to wait. import lancelot def handle_client(client_sock): try: while True: question = lancelot.recv_until(client_sock, "?") answer = lancelot.qadict[question] client_sock.sendall(answer) except EOFError: client_sock.close() def server_loop(listen_sock): while True: client_sock, sockname = listen_sock.accept() handle_client(client_sock) if __name__ == "__main__": listen_sock = lancelot.setup() server_loop(listen_sock)
# Foundations of Python Network Programming - Chapter 7 - server_async.py # Using the ancient "asyncore" framework to write a server. import asyncore, asynchat, lancelot class LancelotRequestHandler(asynchat.async_chat): def __init__(self, sock): asynchat.async_chat.__init__(self, sock) self.set_terminator(b'?') self.data = b'' def collect_incoming_data(self, more_data): self.data += more_data def found_terminator(self): answer = dict(lancelot.qa)[self.data + b'?'] self.push(answer) self.initiate_send() self.data = b'' class LancelotServer(asyncore.dispatcher): def handle_accept(self): sock, address = self.accept() LancelotRequestHandler(sock) sock = lancelot.setup() ls = LancelotServer(sock) ls.accepting = True # since we already called listen() asyncore.loop()
#!/usr/bin/env python # Foundations of Python Network Programming - Chapter 7 - server_poll.py # An event-driven approach to serving several clients with poll(). import lancelot import select listen_sock = lancelot.setup() sockets = {listen_sock.fileno(): listen_sock} requests = {} responses = {} poll = select.poll() poll.register(listen_sock, select.POLLIN) while True: for fd, event in poll.poll(): sock = sockets[fd] # Removed closed sockets from our list. if event & (select.POLLHUP | select.POLLERR | select.POLLNVAL): poll.unregister(fd) del sockets[fd] requests.pop(sock, None) responses.pop(sock, None) # Accept connections from new sockets. elif sock is listen_sock: newsock, sockname = sock.accept() newsock.setblocking(False) fd = newsock.fileno()
import asyncore, asynchat, lancelot class LancelotRequestHandler(asynchat.async_chat): def __init__(self, sock): asynchat.async_chat.__init__(self, sock) self.set_terminator('?') self.data = '' def collect_incoming_data(self, more_data): self.data += more_data def found_terminator(self): answer = dict(lancelot.qa)[self.data + '?'] self.push(answer) self.initiate_send() self.data = '' class LancelotServer(asyncore.dispatcher): def handle_accept(self): sock, address = self.accept() LancelotRequestHandler(sock) sock = lancelot.setup() ls = LancelotServer(sock) ls.accepting = True # since we already called listen() asyncore.loop()