Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Pyro.core
- from time import sleep
- 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
- #connect to our pyro RPC service where we can grab our status and send commands
- cmd = Pyro.core.getProxyForURI("PYROLOC://localhost:7766/cmd")
- class EchoServerProtocol(WebSocketServerProtocol):
- def onOpen(self):
- counter=0
- self.sendMessage(cmd.outputStatus())
- self.factory.register(self)
- def connectionLost(self, reason):
- WebSocketServerProtocol.connectionLost(self, reason)
- self.factory.unregister(self)
- # parse your data from the webapp here when it sends a message
- def onMessage(self,msg,binary):
- status = cmd.outputStatus()
- #check to see if is a length of 1. since we send the bit we want to turn on not much parsing is needed.
- if(len(msg)==1):
- if(status[int(msg)]=='1'):
- cmd.outputCmd(int(msg),0)
- else:
- cmd.outputCmd(int(msg),1)
- 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.data=cmd.outputStatus()
- self.tick()
- #set up a tick that we will use to have the server send the status if it ever changes.
- #update rate set to sleep for .05 seconds. we also send out every 100 ticks just in case the message never arrived
- def tick(self):
- if(self.data!=cmd.outputStatus() or self.tickcount>100):
- self.data=cmd.outputStatus()
- self.sendData(self.data+'-'+str(self.tickcount))
- self.tickcount=0
- self.tickcount=self.tickcount + 1
- reactor.callLater(.05,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 sendData(self,data):
- # send data to each of the connected clients
- for c in self.clients:
- c.sendMessage(data)
- if __name__ == '__main__':
- ServerFactory = BroadcastServerFactory
- factory = ServerFactory("ws://localhost:9000",debug = False)
- factory.protocol = EchoServerProtocol
- listenWS(factory)
- reactor.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement