tcp.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 tornado.tcpserver import TCPServer
  12. from tornado.ioloop import IOLoop
  13. class Connection(object):
  14. clients = set()
  15. def __init__(self, stream, address):
  16. Connection.clients.add(self)
  17. self._stream = stream
  18. self._address = address
  19. self._stream.set_close_callback(self.on_close)
  20. self.read_message()
  21. def read_message(self):
  22. self._stream.read_until('\n', self.broadcast_messages)
  23. def broadcast_messages(self, data):
  24. pub = Pub()
  25. temp = data.split(':')
  26. key = temp[0]
  27. value = temp[1]
  28. pub.push(key, value)
  29. #print "User said:", data[:-1], self._address
  30. """
  31. for conn in Connection.clients:
  32. conn.send_message(data)
  33. """
  34. self.read_message()
  35. def send_message(self, data):
  36. self._stream.write(data)
  37. def on_close(self):
  38. #print "A user has left the chat room.", self._address
  39. Connection.clients.remove(self)
  40. class Server(TCPServer):
  41. def handle_stream(self, stream, address):
  42. #print "New connection :", address, stream
  43. Connection(stream, address)
  44. #print "connection num is:", len(Connection.clients)
  45. class Client(object):
  46. HOST = '0.0.0.0' # The remote host
  47. PORT = 8000 # The same port as used by the server
  48. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  49. s.connect((HOST, PORT))
  50. s.sendall('Hello, \nw')
  51. time.sleep(5)
  52. s.sendall('ord! \n')
  53. data = s.recv(1024)
  54. print 'Received', repr(data)
  55. time.sleep(60)
  56. s.close()