server.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. demeter tcp
  5. name:server.py
  6. author:rabin
  7. """
  8. from demeter import *
  9. from tornado.tcpserver import TCPServer
  10. from tornado.ioloop import IOLoop
  11. class Connection(object):
  12. clients = set()
  13. def __init__(self, stream, address):
  14. Connection.clients.add(self)
  15. self._stream = stream
  16. self._address = address
  17. self._stream.set_close_callback(self.on_close)
  18. self.read_message()
  19. print "A new user has entered the chat room.", address
  20. def read_message(self):
  21. self._stream.read_until('\n', self.broadcast_messages)
  22. def broadcast_messages(self, data):
  23. pub = Pub()
  24. key = ''
  25. value = ''
  26. pub.push(key, value)
  27. print "User said:", data[:-1], self._address
  28. for conn in Connection.clients:
  29. conn.send_message(data)
  30. self.read_message()
  31. def send_message(self, data):
  32. self._stream.write(data)
  33. def on_close(self):
  34. print "A user has left the chat room.", self._address
  35. Connection.clients.remove(self)
  36. class Server(TCPServer):
  37. def handle_stream(self, stream, address):
  38. #print "New connection :", address, stream
  39. Connection(stream, address)
  40. #print "connection num is:", len(Connection.clients)