tcp.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. demeter tcp
  5. name:server.py
  6. author:rabin
  7. """
  8. import socket
  9. import time
  10. from demeter.core import *
  11. from demeter.mqtt import *
  12. from tornado.tcpserver import TCPServer
  13. from tornado.ioloop import IOLoop
  14. from tornado import stack_context
  15. from tornado.escape import native_str
  16. class Connection(object):
  17. clients = set()
  18. EOF = '|e|'
  19. def __init__(self, stream, address):
  20. Connection.clients.add(self)
  21. self._pub = Pub()
  22. self._stream = stream
  23. self._address = address
  24. self._stream.set_close_callback(self.on_close)
  25. self.read_message()
  26. def read_message(self):
  27. self._message_callback = stack_context.wrap(self.on_message)
  28. self._stream.read_until(self.EOF, self._message_callback)
  29. def on_message(self, data):
  30. data = data.replace(self.EOF, '')
  31. temp = data.split('|:|')
  32. key = temp[0]
  33. value = temp[1]
  34. self._pub.push(key, value)
  35. #print "User said:", data[:-1], self._address
  36. """
  37. for conn in Connection.clients:
  38. conn.send_message(data)
  39. """
  40. self.read_message()
  41. def send_message(self, data):
  42. self._stream.write(data)
  43. def on_close(self):
  44. #print "A user has left the chat room.", self._address
  45. Connection.clients.remove(self)
  46. class Server(TCPServer):
  47. def handle_stream(self, stream, address):
  48. #print "New connection :", address, stream
  49. Connection(stream, address)
  50. #print "connection num is:", len(Connection.clients)
  51. class Client(object):
  52. EOF = '|e|'
  53. def __init__(self, host='0.0.0.0', port=8000):
  54. self.connect = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  55. self.connect.connect((host, port))
  56. def send(self, msg):
  57. msg = msg + self.EOF
  58. self.connect.sendall(msg)
  59. #data = self.connect.recv(1024)
  60. def close(self):
  61. self.connect.close()