Skip to content

Instantly share code, notes, and snippets.

@flexd
Created July 11, 2013 10:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save flexd/448b4f3fb90a8f4858b7 to your computer and use it in GitHub Desktop.
Save flexd/448b4f3fb90a8f4858b7 to your computer and use it in GitHub Desktop.
import sys
from twisted.internet import reactor
from twisted.python import log
from twisted.web.server import Site
from twisted.web.static import File
from autobahn.websocket import WebSocketServerFactory, \
WebSocketServerProtocol, \
listenWS
import redis
import websocket
class BroadcastServerProtocol(WebSocketServerProtocol):
def onOpen(self):
self.factory.register(self)
#def onMessage(self, msg, binary):
#if not binary:
#self.factory.broadcast("'%s' from %s" % (msg, self.peerstr))
def connectionLost(self, reason):
WebSocketServerProtocol.connectionLost(self, reason)
self.factory.unregister(self)
class BroadcastServerFactory(WebSocketServerFactory):
def __init__(self, url, debug = False, debugCodePaths = False):
WebSocketServerFactory.__init__(self, url, debug = debug, debugCodePaths = debugCodePaths)
self.clients = []
#self.tickcount = 0
#self.tick()
#def tick(self):
#self.tickcount += 1
#self.broadcast("'tick %d' from server" % self.tickcount)
#reactor.callLater(1, self.tick)
def register(self, client):
if not client in self.clients:
print "registered client " + client.peerstr
self.clients.append(client)
def unregister(self, client):
if client in self.clients:
print "unregistered client " + client.peerstr
self.clients.remove(client)
def broadcast(self, msg):
print "broadcasting message '%s' .." % msg
for c in self.clients:
c.sendMessage(msg)
print "message sent to " + c.peerstr
def redis_listener():
r = redis.Redis().pubsub()
r.subscribe('broadcasts')
for message in r.listen():
#print message['data']
factory.broadcast(message['data'])
ServerFactory = websocket.BroadcastServerFactory
factory = ServerFactory("ws://localhost:9000",
debug=True,
debugCodePaths=True)
factory.protocol = websocket.BroadcastServerProtocol
factory.setProtocolOptions(allowHixie76=True)
if __name__ == '__main__':
listenWS(factory)
reactor.callInThread(redis_listener)
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment