Advertisement
Guest User

Untitled

a guest
Jul 29th, 2015
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. from twisted.internet.protocol import Factory
  3. from twisted.protocols.basic import LineReceiver
  4. from twisted.internet import reactor
  5. import socket
  6. import time
  7.  
  8.  
  9. class UplinkConnection:
  10. def __init__(self, host, port):
  11. self.host = host
  12. self.port = port
  13.  
  14. self._socket = None
  15. self._reconnect()
  16.  
  17. def _reconnect(self):
  18. self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  19. self._socket.connect((self.host, self.port))
  20.  
  21. def send(self, path, value, timestamp):
  22. try:
  23. send_string = "{path} {value} {timestamp}\n".format(path=path, value=value, timestamp=timestamp)
  24. print(send_string)
  25. self._socket.sendall(send_string)
  26. except socket.error:
  27. self._reconnect()
  28.  
  29.  
  30. class Chat(LineReceiver):
  31. def connectionMade(self):
  32. print("New connection from {}".format(self))
  33.  
  34. def lineReceived(self, line):
  35. global uplink
  36. try:
  37. path, value = line.split(' ', 2)
  38. timestamp = int(time.time())
  39. uplink.send(path, value, timestamp)
  40. except ValueError:
  41. pass
  42.  
  43.  
  44. class ChatFactory(Factory):
  45. def buildProtocol(self, addr):
  46. return Chat()
  47.  
  48.  
  49. if __name__ == "__main__":
  50. uplink = UplinkConnection("127.0.0.1", 2003)
  51.  
  52. reactor.listenTCP(2005, ChatFactory())
  53. reactor.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement