listing24-4.py 973 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. from asyncore import dispatcher
  2. from asynchat import async_chat
  3. import socket, asyncore
  4. PORT = 5005
  5. class ChatSession(async_chat):
  6. def __init__(self, sock):
  7. async_chat. init (self, sock)
  8. self.set_terminator("\r\n")
  9. self.data = []
  10. def collect_incoming_data(self, data):
  11. self.data.append(data)
  12. def found_terminator(self):
  13. line = ''.join(self.data)
  14. self.data = []
  15. # Do something with the line...
  16. print(line)
  17. class ChatServer(dispatcher):
  18. def __init__(self, port): dispatcher. init (self)
  19. self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
  20. self.set_reuse_addr()
  21. self.bind(('', port))
  22. self.listen(5)
  23. self.sessions = []
  24. def handle_accept(self):
  25. conn, addr = self.accept()
  26. self.sessions.append(ChatSession(conn))
  27. if __name__ == '__main__':
  28. s = ChatServer(PORT)
  29. try: asyncore.loop()
  30. except KeyboardInterrupt: print()