server.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. def read_message(self):
  20. self._stream.read_until('\n', self.broadcast_messages)
  21. def broadcast_messages(self, data):
  22. pub = Pub()
  23. temp = data.split(':')
  24. key = temp[0]
  25. value = temp[1]
  26. pub.push(key, value)
  27. #print "User said:", data[:-1], self._address
  28. """
  29. for conn in Connection.clients:
  30. conn.send_message(data)
  31. """
  32. self.read_message()
  33. def send_message(self, data):
  34. self._stream.write(data)
  35. def on_close(self):
  36. #print "A user has left the chat room.", self._address
  37. Connection.clients.remove(self)
  38. class Server(TCPServer):
  39. def handle_stream(self, stream, address):
  40. #print "New connection :", address, stream
  41. Connection(stream, address)
  42. #print "connection num is:", len(Connection.clients)