SHARE
TWEET

Untitled

a guest Jan 3rd, 2016 1,722 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import sys
  2. import random
  3.  
  4. from twisted.web.static import File
  5. from twisted.python import log
  6. from twisted.web.server import Site
  7. from twisted.internet import reactor
  8.  
  9. from autobahn.twisted.websocket import WebSocketServerFactory, \
  10.     WebSocketServerProtocol
  11.  
  12. from autobahn.twisted.resource import WebSocketResource
  13.  
  14.  
  15. class SomeServerProtocol(WebSocketServerProtocol):
  16.     def onOpen(self):
  17.         """
  18.        Connection from client is opened. Fires after opening
  19.        websockets handshake has been completed and we can send
  20.        and receive messages.
  21.  
  22.        Register client in factory, so that it is able to track it.
  23.        Try to find conversation partner for this client.
  24.        """
  25.         self.factory.register(self)
  26.         self.factory.findPartner(self)
  27.  
  28.     def connectionLost(self, reason):
  29.         """
  30.        Client lost connection, either disconnected or some error.
  31.        Remove client from list of tracked connections.
  32.        """
  33.         self.factory.unregister(self)
  34.  
  35.     def onMessage(self, payload, isBinary):
  36.         """
  37.        Message sent from client, communicate this message to its conversation partner,
  38.        """
  39.         self.factory.communicate(self, payload, isBinary)
  40.  
  41.  
  42.  
  43. class ChatRouletteFactory(WebSocketServerFactory):
  44.     def __init__(self, *args, **kwargs):
  45.         super(ChatRouletteFactory, self).__init__(*args, **kwargs)
  46.         self.clients = {}
  47.  
  48.     def register(self, client):
  49.         """
  50.        Add client to list of managed connections.
  51.        """
  52.         self.clients[client.peer] = {"object": client, "partner": None}
  53.  
  54.     def unregister(self, client):
  55.         """
  56.        Remove client from list of managed connections.
  57.        """
  58.         self.clients.pop(client.peer)
  59.  
  60.     def findPartner(self, client):
  61.         """
  62.        Find chat partner for a client. Check if there any of tracked clients
  63.        is idle. If there is no idle client just exit quietly. If there is
  64.        available partner assign him/her to our client.
  65.        """
  66.         available_partners = [c for c in self.clients if c != client.peer and not self.clients[c]["partner"]]
  67.         if not available_partners:
  68.             print("no partners for {} check in a moment".format(client.peer))
  69.         else:
  70.             partner_key = random.choice(available_partners)
  71.             self.clients[partner_key]["partner"] = client
  72.             self.clients[client.peer]["partner"] = self.clients[partner_key]["object"]
  73.  
  74.     def communicate(self, client, payload, isBinary):
  75.         """
  76.        Broker message from client to its partner.
  77.        """
  78.         c = self.clients[client.peer]
  79.         if not c["partner"]:
  80.             c["object"].sendMessage("Sorry you dont have partner yet, check back in a minute")
  81.         else:
  82.             c["partner"].sendMessage(payload)
  83.  
  84.  
  85. if __name__ == "__main__":
  86.     log.startLogging(sys.stdout)
  87.  
  88.     # static file server seving index.html as root
  89.     root = File(".")
  90.  
  91.     factory = ChatRouletteFactory(u"ws://127.0.0.1:8080", debug=True)
  92.     factory.protocol = SomeServerProtocol
  93.     resource = WebSocketResource(factory)
  94.     # websockets resource on "/ws" path
  95.     root.putChild(u"ws", resource)
  96.  
  97.     site = Site(root)
  98.     reactor.listenTCP(8080, site)
  99.     reactor.run()
RAW Paste Data
Want to get better at Python?
Learn to code Python in 2017
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top