Ejemplo n.º 1
0
    def startService(self):

        factory = WebSocketServerFactory("ws://localhost:%d" % self.port,
                                         debug=self.debug)

        factory.protocol = EchoServerProtocol
        factory.setProtocolOptions(
            allowHixie76=True)  # needed if Hixie76 is to be supported

        # FIXME: Site.start/stopFactory should start/stop factories wrapped as Resources
        factory.startFactory()

        resource = WebSocketResource(factory)

        # we server static files under "/" ..
        webdir = os.path.abspath(
            pkg_resources.resource_filename("echows", "web"))
        root = File(webdir)

        # and our WebSocket server under "/ws"
        root.putChild("ws", resource)

        # both under one Twisted Web Site
        site = Site(root)
        site.protocol = HTTPChannelHixie76Aware  # needed if Hixie76 is to be supported

        self.site = site
        self.factory = factory

        self.listener = reactor.listenTCP(self.port, site)
    def startService(self):

        factory = WebSocketServerFactory(u"ws://127.0.0.1:%d" % self.port)
        factory.protocol = EchoServerProtocol

        # FIXME: Site.start/stopFactory should start/stop factories wrapped as Resources
        factory.startFactory()

        resource = WebSocketResource(factory)

        # we server static files under "/" ..
        webdir = os.path.abspath(pkg_resources.resource_filename("echows", "web"))
        root = File(webdir)

        # and our WebSocket server under "/ws" (note that Twisted uses
        # bytes for URIs)
        root.putChild(b"ws", resource)

        # both under one Twisted Web Site
        site = Site(root)

        self.site = site
        self.factory = factory

        self.listener = reactor.listenTCP(self.port, site)
Ejemplo n.º 3
0
def main(curDir):
    class WhiteboardServerProtocol(WebSocketServerProtocol):
        def onConnect(self, connectionRequest):
            whiteboard.addClient(self)
            return None

        def onMessage(self, msg, binary):
            whiteboard.processMessage(self, msg)

    os.chdir(curDir)
    
    #log.startLogging(sys.stdout)
    debugWS = False
    debugWhiteboard = False
    whiteboard = WhiteboardServer(debugWhiteboard)

    factory = WebSocketServerFactory("ws://localhost:9000",
                                     debug = debugWS,
                                     debugCodePaths = debugWS)

    factory.protocol = WhiteboardServerProtocol
    #factory.setProtocolOptions(allowHixie76 = True)
    listenWS(factory)

    webdir = File(".")
    web = Site(webdir)
    reactor.listenTCP(8080, web)

    #threading.Thread(None, reactor.run, None).start()
    print "Starting websocket server"
    reactor.run()

    whiteboard.shutdown()
Ejemplo n.º 4
0
    def startService(self):

        factory = WebSocketServerFactory("ws://localhost:%d" % self.port, debug=self.debug)

        factory.protocol = EchoServerProtocol
        factory.setProtocolOptions(allowHixie76=True)  # needed if Hixie76 is to be supported

        # FIXME: Site.start/stopFactory should start/stop factories wrapped as Resources
        factory.startFactory()

        resource = WebSocketResource(factory)

        # we server static files under "/" ..
        webdir = os.path.abspath(pkg_resources.resource_filename("echows", "web"))
        root = File(webdir)

        # and our WebSocket server under "/ws"
        root.putChild("ws", resource)

        # both under one Twisted Web Site
        site = Site(root)
        site.protocol = HTTPChannelHixie76Aware  # needed if Hixie76 is to be supported

        self.site = site
        self.factory = factory

        self.listener = reactor.listenTCP(self.port, site)
Ejemplo n.º 5
0
def main():
    """ Main method for the websocket server """
    LOG.info('main: Start')
    udp_steward = UDPConnectionSteward()
    udp_steward.start()

    # Uncomment these two to get log from twisted
    #import sys
    #log.startLogging(sys.stdout)
    # Create context factor with key and certificate
    context_factory = ssl.DefaultOpenSSLContextFactory(
        '/home/kenni/Dokumenter/websockets/autobahn/keys/server.key',
        '/home/kenni/Dokumenter/websockets/autobahn/keys/server.crt'
    )
    # Form the webserver factory
    factory = WebSocketServerFactory("wss://localhost:9001", debug=True)
    # Set the handler
    factory.protocol = CinfWebSocketHandler
    # Listen for incoming WebSocket connections: wss://localhost:9001
    listenWS(factory, context_factory)

    try:
        reactor.run()  # pylint: disable=E1101
        time.sleep(1)
        LOG.info('main: Keyboard interrupt, websocket reactor stopped')
        udp_steward.stop()
        time.sleep(1)
        LOG.info('main: UPD Steward stopped')
    except Exception as exception_:
        LOG.exception(exception_)
        raise exception_

    LOG.info('main: Ended')
    raw_input('All stopped. Press enter to exit')
Ejemplo n.º 6
0
    def startService(self):

        factory = WebSocketServerFactory("ws://127.0.0.1:%d" % self.port)
        factory.protocol = EchoServerProtocol

        # FIXME: Site.start/stopFactory should start/stop factories wrapped as Resources
        factory.startFactory()

        resource = WebSocketResource(factory)

        # we server static files under "/" ..
        webdir = os.path.abspath(pkg_resources.resource_filename("echows", "web"))
        root = File(webdir)

        # and our WebSocket server under "/ws" (note that Twisted uses
        # bytes for URIs)
        root.putChild(b"ws", resource)

        # both under one Twisted Web Site
        site = Site(root)

        self.site = site
        self.factory = factory

        self.listener = reactor.listenTCP(self.port, site)
Ejemplo n.º 7
0
def main(curDir):
    class WhiteboardServerProtocol(WebSocketServerProtocol):
        def onConnect(self, connectionRequest):
            whiteboard.addClient(self)
            return None

        def onMessage(self, msg, binary):
            whiteboard.processMessage(self, msg)

    os.chdir(curDir)

    #log.startLogging(sys.stdout)
    debugWS = False
    debugWhiteboard = False
    whiteboard = WhiteboardServer(debugWhiteboard)

    factory = WebSocketServerFactory("ws://localhost:9000",
                                     debug=debugWS,
                                     debugCodePaths=debugWS)

    factory.protocol = WhiteboardServerProtocol
    #factory.setProtocolOptions(allowHixie76 = True)
    listenWS(factory)

    webdir = File(".")
    web = Site(webdir)
    reactor.listenTCP(8080, web)

    #threading.Thread(None, reactor.run, None).start()
    print "Starting websocket server"
    reactor.run()

    whiteboard.shutdown()
Ejemplo n.º 8
0
    def serve_wss(self):
        """Start a web socket server over SSL, used by the web UI to get notifications about updates."""
        import os
        from .events import SystemEvent

        # Start a web socket server if the web UI is enabled
        if not self._config['web-ui-enabled']:
            return

        if not self._config['wss-enabled']:
            return

        if not os.path.isfile(self._config['ssl-cert']):
            self._startup_event.log_critical("Unable to activate SSL: File does not exist: %s" % self._config['ssl-cert'])
            return

        try:
            import os
            from autobahn.websocket import WebSocketServerProtocol, WebSocketServerFactory
            from twisted.internet import reactor, ssl
            from twisted.internet.error import BindError

            # Create a WebSocketClientHandler instance
            WebSocketClientHandler = WebSocketClientHandlerFactory(self._config, self._ws_clients, self._event_store, self._server_status)

            uri = u"ws://%s:%s" % (self._config['wss-host'], self._config['wss-port'])
            factory = WebSocketServerFactory(uri)
            factory.protocol = WebSocketClientHandler
            # factory.setProtocolOptions(maxConnections=2)

            # note to self: if using putChild, the child must be bytes...
            if self._config['ssl-key'] and self._config['ssl-cert']:
                contextFactory = ssl.DefaultOpenSSLContextFactory(privateKeyFileName=self._config['ssl-key'], certificateFileName=self._config['ssl-cert'])
            else:
                contextFactory = ssl.DefaultOpenSSLContextFactory(privateKeyFileName=self._config['ssl-cert'], certificateFileName=self._config['ssl-cert'])


            self._ws_server_port = reactor.listenSSL(self._config['wss-port'], factory, contextFactory)
            # self._ws_server_port = reactor.listenTCP(self._config['wss-port'], factory)

            self._server_status['wss-uri'] = "wss://%s:%s" % (self._config['wss-host'], self._config['wss-port'])

            self._startup_event.log_info("Listening for connections on %s" % self._server_status['wss-uri'])
            self._startup_event.ws_address = self._config['wss-host']
            self._startup_event.ws_port = self._config['wss-port']
            self._startup_event.set_ws_started(True)

            # Serve forever (until reactor.stop())
            reactor.run(installSignalHandlers=False)

        except BindError as e:
            self._startup_event.log_critical("Unable to start web socket server: %s" % e)

        except ImportError:
            self._startup_event.log_error("Unable to start web socket server due to missing dependency.")

        event = SystemEvent()
        self._event_store.register_action(event)
        event.log_info('WSS server did quit')
Ejemplo n.º 9
0
def main():

   log.startLogging(sys.stdout)

   factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
   factory.protocol = EchoServerProtocol
   listenWS(factory)

   reactor.run()
Ejemplo n.º 10
0
Archivo: live.py Proyecto: gimzo/kwizz
 def __init__(self):
    global kwizz
    kwizz=self
    self.players=[]
    self.games=[]
    factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
    factory.protocol = KwizzLiveProtocol
    reactor.listenTCP(9000, factory)
    reactor.run()
Ejemplo n.º 11
0
    def serve_wss(self):
        """Start a web socket server over SSL, used by the web UI to get notifications about updates."""
        import os
        from .events import SystemEvent
        from autobahn.websocket import WebSocketServerProtocol, WebSocketServerFactory
        from twisted.internet import reactor
        from twisted.internet.error import BindError

        # Start a web socket server if the web UI is enabled
        if not self._config['web-ui-enabled']:
            return

        if not self._config['wss-enabled']:
            return

        if not os.path.isfile(self._config['ssl-cert']):
            self._startup_event.log_critical("Unable to activate SSL: File does not exist: %s" % self._config['ssl-cert'])
            return

        from twisted.internet import ssl

        try:
            # Create a WebSocketClientHandler instance
            WebSocketClientHandler = WebSocketClientHandlerFactory(self._config, self._ws_clients, self._event_store, self._server_status)

            uri = u"ws://%s:%s" % (self._config['wss-host'], self._config['wss-port'])
            factory = WebSocketServerFactory(uri)
            factory.protocol = WebSocketClientHandler
            # factory.setProtocolOptions(maxConnections=2)

            # note to self: if using putChild, the child must be bytes...
            if self._config['ssl-key'] and self._config['ssl-cert']:
                contextFactory = ssl.DefaultOpenSSLContextFactory(privateKeyFileName=self._config['ssl-key'], certificateFileName=self._config['ssl-cert'])
            else:
                contextFactory = ssl.DefaultOpenSSLContextFactory(privateKeyFileName=self._config['ssl-cert'], certificateFileName=self._config['ssl-cert'])

            self._ws_server_port = reactor.listenSSL(self._config['wss-port'], factory, contextFactory)

            self._server_status['wss-uri'] = "wss://%s:%s" % (self._config['wss-host'], self._config['wss-port'])

            self._startup_event.log_info(u"Escutando conexões em %s" % self._server_status['wss-uri'])
            self._startup_event.ws_address = self._config['wss-host']
            self._startup_event.ws_port = self._config['wss-port']
            self._startup_event.set_ws_started(True)

            # Serve forever (until reactor.stop())
            reactor.run(installSignalHandlers=False)

        except BindError as e:
            self._startup_event.log_critical("Unable to start web socket server: %s" % e)

        except ImportError:
            self._startup_event.log_error("Unable to start web socket server due to missing dependency.")

        event = SystemEvent()
        self._event_store.register_action(event)
        event.log_info('WSS server did quit')
Ejemplo n.º 12
0
def startServer():
    output = getoutput('ifconfig wlan0')
    if 'inet addr:' in output:
        print 'wlan0 already connected!'
        return

    factory = WebSocketServerFactory(u"ws://127.0.0.1:9000")
    factory.protocol = SetupWifiWebsocketProtocol
    reactor.listenTCP(9000, factory)

    reactor.run()
Ejemplo n.º 13
0
	def run ( self ):
			log.startLogging(sys.stdout)

			factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
			factory.protocol = PushServerProtocol
			listenWS(factory)
			
			reactor.run()
			
			
			
Ejemplo n.º 14
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", "--port", metavar="PORT=3000", type=int, default=3000)
    myapp.setup_argparser(parser)
    args = parser.parse_args()
    myapp.setup_app(args)
    
    factory = WebSocketServerFactory("ws://localhost:%d" % args.port)
    factory.protocol = WebSocketWrapperProtocol
    
    root = Root()
    root.putChild("ws", WebSocketResource(factory))
    reactor.listenTCP(args.port, Site(root))
    reactor.run()
Ejemplo n.º 15
0
def start_server(port, appmanager, protocol, apprate, netrate):
    port = 9999
    manager = Manager(appmanager, apprate, netrate)  # TODO remove manager = ?

    DefaultConnection.__bases__ += (Protocol, protocol, Sender)  # WTF inheritance
    echofactory = Factory()
    echofactory.protocol = DefaultConnection
    reactor.listenTCP(port, echofactory)
    # WEBSOOOOOCKKEEEET
    WSConnection.__bases__ += (WebSocketServerProtocol, protocol, Sender)
    factory = WebSocketServerFactory("ws://localhost:" + str(port + 1))
    factory.protocol = WSConnection
    listenWS(factory)
    print "Server initialized"
    reactor.run()
Ejemplo n.º 16
0
def getAutoBahn(core, port=80):
   #from twisted.python import log as tlog
   #tlog.startLogging(sys.stdout)

   wsuri = "ws://localhost"
   if not port in ['80','443']:
      wsuri+=":"+str(port)
   #factory = WebSocketServerFactory(wsuri, debug=True, debugCodePaths=True)
   factory = WebSocketServerFactory(wsuri)
   factory.core = core
   factory.protocol = AutobahnProtocolWrapper
   factory.setProtocolOptions(allowHixie76 = True)
   resource = WebSocketResource(factory)
   log.debug("AutoBahn started")
   return resource
Ejemplo n.º 17
0
def start_web(localEPG=None, playout_service=None, playout=None, port=8888, schedule=None):
	root = File('web')
	if schedule:
		root.putChild("schedules", SchedulesPage(schedule))
		root.putChild("player_snapshots", File('cache/snapshots'))
	root.putChild("stills", StillsListPage("stills"))
	wrapper = simple_guard_resource(root)
	site = Site(wrapper)
	reactor.listenTCP(port, site)


	factory = WebSocketServerFactory()
	factory.protocol = lambda: PlayoutWebsocketProtocol (playout_service, playout, schedule)
	reactor.listenTCP(8889, factory)

	"""
Ejemplo n.º 18
0
 def _setUpListener(self, serviceName, port, protocol, handler=None):
     url = "ws://localhost:%d"%(port)       
     factory = WebSocketServerFactory(url, debug=True, debugCodePaths=True)    
     factory.protocol = protocol
     factory.setProtocolOptions(allowHixie76=True)
     
     #HACK: add an array for observing messages
     factory.observers = [] #called for every message; for the ui to listen
     
     if handler !=None:
         factory.observers.append(handler)
     
     factory.connections = [] #all connections that are active; for the protocol to send data
     self.frontEndListeners[serviceName] = factory
     listenWS(self.frontEndListeners[serviceName]) 
     
Ejemplo n.º 19
0
def main():
    """ Main method for the websocket server """
    # Uncomment these two to get log from twisted
    #import sys
    #log.startLogging(sys.stdout)
    # Create context factor with key and certificate

    # Start UDP server thread
    udp_server = ReceiveDataUDPServer()
    udp_server.start()

    # Start load monitor thread
    load_monitor = LoadMonitor()
    load_monitor.start()

    # Start the data sender thread
    data_sender = DataSender()
    data_sender.start()

    ####### SSL IMPLEMENTATION
    context_factory = ssl.DefaultOpenSSLContextFactory(
        '/home/kenni/certs/fysik.dtu.dk.key',
        '/home/kenni/certs/fysik.dtu.dk-NEW.crt'
    )
    # Form the webserver factory
    factory = WebSocketServerFactory("wss://localhost:9002", debug=True)
    # Set the handler
    factory.protocol = CinfWebSocketHandler
    # Listen for incoming WebSocket connections: wss://localhost:9002
    listenWS(factory, context_factory)
    ######## SSL IMPLEMENTATION END

    try:
        LOG.info('run reactor')
        reactor.run()  # pylint: disable=E1101
    except Exception as exception_:
        LOG.exception(exception_)
        raise exception_

    # Stop all three threads
    udp_server.stop()
    load_monitor.stop()
    data_sender.stop()

    LOG.info('main: Ended')
    #raw_input('All stopped. Press enter to exit')
    print('All stopped. Press enter to exit')
Ejemplo n.º 20
0
    def serve_ws(self):
        """Start a web socket server, used by the web UI to get notifications about updates."""
        import os
        from .events import SystemEvent
        from autobahn.websocket import WebSocketServerProtocol, WebSocketServerFactory
        from twisted.internet import reactor
        from twisted.internet.error import BindError

        # Start a web socket server if the web UI is enabled
        if not self._config['web-ui-enabled']:
            return

        if not self._config['ws-enabled']:
            return

        try:
            # Create a WebSocketClientHandler instance
            WebSocketClientHandler = WebSocketClientHandlerFactory(self._config, self._ws_clients, self._event_store, self._server_status)

            uri = u"ws://%s:%s" % (self._config['ws-host'], self._config['ws-port'])
            factory = WebSocketServerFactory(uri)
            factory.protocol = WebSocketClientHandler
            # factory.setProtocolOptions(maxConnections=2)

            self._ws_server_port = reactor.listenTCP(self._config['ws-port'], factory)

            self._server_status['wss-uri'] = "ws://%s:%s" % (self._config['ws-host'], self._config['ws-port'])

            self._startup_event.log_info(u"Escutando conexões em %s" % self._server_status['wss-uri'])
            self._startup_event.ws_address = self._config['ws-host']
            self._startup_event.ws_port = self._config['ws-port']
            self._startup_event.set_ws_started(True)

            # Serve forever (until reactor.stop())
            reactor.run(installSignalHandlers=False)

        except BindError as e:
            self._startup_event.log_critical("Unable to start web socket server: %s" % e)

        except ImportError:
            self._startup_event.log_error("Unable to start web socket server due to missing dependency.")

        event = SystemEvent()
        self._event_store.register_action(event)
        event.log_info('WS server did quit')
Ejemplo n.º 21
0
def main():
	try:
		#initializing serial flashing etc utilities socket
		ServerFactory = BroadcastServerFactory

		factory = ServerFactory("ws://localhost:9000")
		# factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
		factory.protocol = EchoServerProtocol
		listenWS(factory)

		factory2 = WebSocketServerFactory("ws://localhost:9001")
		factory2.protocol = WebSerialProtocol
		listenWS(factory2)

		reactor.run()
	except error.CannotListenError, e:
		print "Port is already used. Exiting..."
		os._exit(0)
Ejemplo n.º 22
0
def main():
    """ Main method for the websocket server """
    LOG.info('main: Start')
    global LIVESOCKET  # pylint: disable=global-statement
    names = ['wss_hosts_defined', 'wss_hosts', 'wss_clients']
    LIVESOCKET = LiveSocket('websocketserver', names, sane_interval=1.0)
    LIVESOCKET.start()

    udp_steward = UDPConnectionSteward()
    udp_steward.start()

    # Uncomment these two to get log from twisted
    #import sys
    #log.startLogging(sys.stdout)
    # Create context factor with key and certificate
    context_factory = ssl.DefaultOpenSSLContextFactory(
        '/home/kenni/certs/fysik.dtu.dk.key',
        '/home/kenni/certs/fysik.dtu.dk-NEW.crt'
    )
    # Form the webserver factory
    factory = WebSocketServerFactory("wss://localhost:9001", debug=True)
    # Set the handler
    factory.protocol = CinfWebSocketHandler
    # Listen for incoming WebSocket connections: wss://localhost:9001
    listenWS(factory, context_factory)

    try:
        reactor.run()  # pylint: disable=E1101
        time.sleep(1)
        LOG.info('main: Keyboard interrupt, websocket reactor stopped')
        udp_steward.stop()
        time.sleep(1)
        LOG.info('main: UPD Steward stopped')
        LIVESOCKET.stop()
        time.sleep(1)
        LOG.info('main: Own livesocket stoppped')
    except Exception as exception_:
        LOG.exception(exception_)
        raise exception_

    LOG.info('main: Ended')
    raw_input('All stopped. Press enter to exit')
Ejemplo n.º 23
0
def main():
    """ Main method for the websocket server """
    LOG.info('main: Start')
    global LIVESOCKET  # pylint: disable=global-statement
    names = ['wss_hosts_defined', 'wss_hosts', 'wss_clients']
    LIVESOCKET = LiveSocket('websocketserver', names, sane_interval=1.0)
    LIVESOCKET.start()

    udp_steward = UDPConnectionSteward()
    udp_steward.start()

    # Uncomment these two to get log from twisted
    #import sys
    #log.startLogging(sys.stdout)
    # Create context factor with key and certificate
    context_factory = ssl.DefaultOpenSSLContextFactory(
        '/home/kenni/certs/fysik.dtu.dk.key',
        '/home/kenni/certs/fysik.dtu.dk.crt'
    )
    # Form the webserver factory
    factory = WebSocketServerFactory("wss://localhost:9001", debug=True)
    # Set the handler
    factory.protocol = CinfWebSocketHandler
    # Listen for incoming WebSocket connections: wss://localhost:9001
    listenWS(factory, context_factory)

    try:
        reactor.run()  # pylint: disable=E1101
        time.sleep(1)
        LOG.info('main: Keyboard interrupt, websocket reactor stopped')
        udp_steward.stop()
        time.sleep(1)
        LOG.info('main: UPD Steward stopped')
        LIVESOCKET.stop()
        time.sleep(1)
        LOG.info('main: Own livesocket stoppped')
    except Exception as exception_:
        LOG.exception(exception_)
        raise exception_

    LOG.info('main: Ended')
    raw_input('All stopped. Press enter to exit')
Ejemplo n.º 24
0
def main(argv):

    try:
        opts, args = getopt.getopt(argv, 'h', ['help'])

    except getopt.GetoptError:
        usage()

    for opt, val in opts:
        if opt in ('-h', '--help'):
            usage()

    print 'The count server is gonna start ...'

    factory = WebSocketServerFactory('ws://localhost:9000')
    factory.protocol = CountServerProtocol
    listenWS(factory)

    reactor.callWhenRunning(countForEver)
    reactor.run()
Ejemplo n.º 25
0
        for data in payload:
            l += len(data)
            self.sha256.update(data)
        digest = self.sha256.hexdigest()
        print "Received frame with payload length %7d, compute digest: %s" % (
            l, digest)
        self.sendMessage(digest)

    def onMessageEnd(self):
        self.sha256 = None


if __name__ == '__main__':

    factory = WebSocketServerFactory("ws://localhost:9000")
    factory.protocol = FrameBasedHashServerProtocol

    enableCompression = True
    if enableCompression:
        from autobahn.compress import PerMessageDeflateOffer, \
                                      PerMessageDeflateOfferAccept

        ## Function to accept offers from the client ..
        def accept(offers):
            for offer in offers:
                if isinstance(offer, PerMessageDeflateOffer):
                    return PerMessageDeflateOfferAccept(offer)

        factory.setProtocolOptions(perMessageCompressionAccept=accept)

    listenWS(factory)
Ejemplo n.º 26
0
    def onMessage(self, msg, binary):
        self.sendMessage("Echo 2 - " + msg)


if __name__ == '__main__':

    if len(sys.argv) > 1 and sys.argv[1] == 'debug':
        log.startLogging(sys.stdout)
        debug = True
    else:
        debug = False

    factory1 = WebSocketServerFactory("ws://localhost:9000",
                                      debug=debug,
                                      debugCodePaths=debug)
    factory1.protocol = Echo1ServerProtocol
    resource1 = WebSocketResource(factory1)

    factory2 = WebSocketServerFactory("ws://localhost:9000",
                                      debug=debug,
                                      debugCodePaths=debug)
    factory2.protocol = Echo2ServerProtocol
    resource2 = WebSocketResource(factory2)

    ## Establish a dummy root resource
    root = Data("", "text/plain")

    ## and our WebSocket servers under different paths ..
    root.putChild("echo1", resource1)
    root.putChild("echo2", resource2)
Ejemplo n.º 27
0
	def isTyping(self):
		self.chatWith.sendMessage("typ:\n")
	
	def isNotTyping(self):
		self.chatWith.sendMessage("pyt:\n")
			
	def message(self, message):
		self.sendMessage("ann:" + message + '\n')
		
	def chatAll(self, message):
		self.sendMessage("out:" + message + '\n')
		self.chatWith.sendMessage("in:" + message + '\n')
		
	def messageAll(self, message):
		self.sendMessage("ann:" + message + '\n')
		self.chatWith.sendMessage("ann:" + message + '\n')
		
	def enableAll(self, message):
		self.sendMessage("con:" + message + '\n')
		self.chatWith.sendMessage("con:" + message + '\n')

urlString = "ws://localhost:" + port
factory = WebSocketServerFactory(urlString)
factory.protocol = Chat
factory.unusedClients = []
factory.chatting = []
listenWS(factory)
print "Chat server started in port " + port
log.msg("Chat server started in port " + port)
reactor.run()
Ejemplo n.º 28
0
from twisted.internet import reactor, ssl
from autobahn.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS


class WebSocketTestServerProtocol(WebSocketServerProtocol):

   def onMessage(self, msg, binary):
      self.sendMessage(msg, binary)


if __name__ == '__main__':

   log.startLogging(sys.stdout)

   ## SSL server context: load server key and certificate
   ##
   contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key', 'keys/server.crt')

   ## create a WS server factory with our protocol
   ##
   factory = WebSocketServerFactory("wss://localhost:9000", debug = False)
   factory.setProtocolOptions(failByDrop = False)
   factory.protocol = WebSocketTestServerProtocol

   ## Listen for incoming WebSocket connections: wss://localhost:9000
   ##
   listenWS(factory, contextFactory)

   log.msg("Using Twisted reactor class %s" % str(reactor.__class__))
   reactor.run()
        reactor.stop()

    ## Handle the CTRL+C signal to shutdown
    signal.signal(signal.SIGINT, KeyboardInterruptHandler)

    ## Create and initialize the NeoPixel library
    logger.info('Loading NeoPixel library...')
    neopixelStrip = neopixel.Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)
    neopixelStrip.begin()

    ## Startup animation

    colorWhite = neopixel.Color(255, 255, 255)
    colorBlack = neopixel.Color(0, 0, 0)

    slideFromLeft(neopixelStrip, colorWhite)
    slideFromRight(neopixelStrip, colorBlack)
    slideFromRight(neopixelStrip, colorWhite)

    pulseBrightness(neopixelStrip, 255, 10)

    logger.info('Starting websocket server...')

    factory = WebSocketServerFactory('ws://' + GATEWAY_ADDRESS + ':' + str(GATEWAY_PORT), debug=False)
    factory.protocol = VibeLightGatewayProtocol

    logger.info('Listening...')

    reactor.listenTCP(GATEWAY_PORT, factory)
    reactor.run()
Ejemplo n.º 30
0
            p = Popen(["python", "fsclient.py",
                       str(SERVERS_PORT[index]), msg],
                      stdout=PIPE,
                      stdin=PIPE,
                      stderr=STDOUT)
            result = p.communicate()[0]
            self.sendMessage(result)
        elif typeMsg == '[R]':
            index = self.__balancer_read(file_name)
            print "[R][%s] Read %s file from DFS" % (time.strftime("%H:%M:%S"),
                                                     file_name)
            p = Popen(["python", "fsclient.py",
                       str(SERVERS_PORT[index]), msg],
                      stdout=PIPE,
                      stdin=PIPE,
                      stderr=STDOUT)
            result = p.communicate()[0]
            self.sendMessage(result)


if __name__ == '__main__':
    import sys
    if len(sys.argv) < 2:
        sys.exit("Using server.py [SERVERS]")
    factory = WebSocketServerFactory("ws://" + ADDRESS + ":" + str(PORT),
                                     debug=False)
    SERVERS = int(sys.argv[1])
    factory.protocol = DFS
    listenWS(factory)
    print 'Server starting up on %s port %s' % (ADDRESS, PORT)
    reactor.run()
Ejemplo n.º 31
0
      self.send_hello = False


if __name__ == '__main__':

   log.startLogging(sys.stdout)

   ## SSL server context: load server key and certificate
   ## We use this for both WS and Web!
   ##
   contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key', 'keys/server.crt')

   ## create a WS server factory with our protocol
   ##
   factory = WebSocketServerFactory("wss://localhost:9000", debug = False)
   factory.protocol = EchoServerProtocol

   ## Listen for incoming WebSocket connections: wss://localhost:9000
   ##
   listenWS(factory, contextFactory)

   ## Setup Web serving (for convenience): https://localhost:9090/
   ##
   webdir = File(".")
   web = Site(webdir)
   reactor.listenSSL(9090, web, contextFactory)

   ## Run everything ..
   ##
   reactor.run()
Ejemplo n.º 32
0
							#print "...applying POS TAG"
							#part_of_speech_tagging(string_to_write)
			else :
				subprocess.call(["espeak","who you are taking to"])

def display_to_console(msg):
	print "\r" + msg


class SpeechServer(WebSocketServerProtocol):
		def onMessage(self,msg,binary):
				display_to_console(msg)	
				apply_nlp(msg)	
				#if(re.search("yes",msg,re.IGNORECASE)):
				#					text=re.sub(r'yes',"",msg)
				



class Agent_rescue:
	def __init__(self,file_location,id,name):
		self.file_location=file_location
		self.id=id
		self.name=name
		self.clips=clips.Environment()


factory=WebSocketServerFactory("ws://localhost:9000",debug=False);
factory.protocol=SpeechServer
listenWS(factory)
reactor.run()
Ejemplo n.º 33
0
                # now that envs are totally complete show results.
                if (len(self.pending_envs) == 0):
                    self.on_envs_complete()

    def onOpen(self):
        self.increment = self.increment + 1
        tests = sys.argv[1:len(sys.argv)]
        self.run_tests(tests)

    def run_tests(self, tests):
        def format(value):
            if (value[0] != '/'):
                value = '/' + value
            return value

        tests = map(format, tests)
        self.emit('run tests', {'tests': tests})

    def onMessage(self, data, binary):
        command = json.loads(data)
        # test agent protocol always uses the [event, data] format.
        self.handle_event(command[0], [command[1]])


if __name__ == '__main__':
    factory = WebSocketServerFactory("ws://localhost:8789")
    factory.protocol = TestAgentServer
    listenWS(factory)
    reactor.run()
Ejemplo n.º 34
0
            file_path = FILES_PATH + file_name
            f = open(file_path, 'w')
            f.write(message)
            f.close()
            print "File %s successfully writen..." % file_name
            self.sendMessage('[C][' + file_name + ']OK')
        elif typeMsg == '[R]':
            print "[R][%s] Read %s file from %s" % (time.strftime("%H:%M:%S"),
                                                    file_name, CATALOG_NAME)
            print "File %s successfully read..." % file_name
            file_path = FILES_PATH + file_name
            f = open(file_path, 'r')
            message = '[O][' + file_name + ']' + f.read()
            f.close()
            self.sendMessage(message)


if __name__ == '__main__':
    import sys
    if len(sys.argv) < 4:
        sys.exit("Using fileserver.py [IP] [PORT] [file_catalog_name]")
    ADDRESS = str(sys.argv[1])
    PORT = int(sys.argv[2])
    CATALOG_NAME = str(sys.argv[3])
    FILES_PATH = '.\\data\\' + CATALOG_NAME + '\\'
    factory = WebSocketServerFactory("ws://" + ADDRESS + ":" + str(PORT),
                                     debug=False)
    factory.protocol = FS
    listenWS(factory)
    print 'Server starting up on %s port %s' % (ADDRESS, PORT)
    reactor.run()
Ejemplo n.º 35
0
##  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
##  See the License for the specific language governing permissions and
##  limitations under the License.
##
###############################################################################

import hashlib
from twisted.internet import reactor
from autobahn.websocket import WebSocketServerFactory, WebSocketServerProtocol


class MessageBasedHashServerProtocol(WebSocketServerProtocol):
   """
   Message-based WebSockets server that computes a SHA-256 for every
   message it receives and sends back the computed digest.
   """

   def onMessage(self, message, binary):
      sha256 = hashlib.sha256()
      sha256.update(message)
      digest = sha256.hexdigest()
      self.sendMessage(digest)
      print "Sent digest for message: %s" % digest


if __name__ == '__main__':
   factory = WebSocketServerFactory()
   factory.protocol = MessageBasedHashServerProtocol
   reactor.listenTCP(9000, factory)
   reactor.run()
##
##      http://www.apache.org/licenses/LICENSE-2.0
##
##  Unless required by applicable law or agreed to in writing, software
##  distributed under the License is distributed on an "AS IS" BASIS,
##  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
##  See the License for the specific language governing permissions and
##  limitations under the License.
##
###############################################################################

import sys
from twisted.python import log
from twisted.internet import reactor
from autobahn.websocket import WebSocketServerFactory, WebSocketServerProtocol


class WebSocketTestServerProtocol(WebSocketServerProtocol):
    def onMessage(self, msg, binary):
        self.sendMessage(msg, binary)


if __name__ == '__main__':

    log.startLogging(sys.stdout)
    factory = WebSocketServerFactory(debug=False)
    factory.failByDrop = False
    factory.protocol = WebSocketTestServerProtocol
    reactor.listenTCP(9000, factory)
    reactor.run()
Ejemplo n.º 37
0
                if (len(self.pending_envs) == 0):
                    self.on_envs_complete();


    def onOpen(self):
        self.increment = self.increment + 1;
        tests = sys.argv[1:len(sys.argv)];
        self.run_tests(tests);

    def run_tests(self, tests):
        def format(value):
            if (value[0] != '/'):
                value = '/' + value
            return value

        tests = map(format, tests)
        self.emit('run tests', { 'tests': tests });

    def onMessage(self, data, binary):
        command = json.loads(data)
        # test agent protocol always uses the [event, data] format.
        self.handle_event(command[0], [command[1]])


if __name__ == '__main__':
    factory = WebSocketServerFactory("ws://localhost:8789")
    factory.protocol = TestAgentServer
    listenWS(factory)
    reactor.run()

Ejemplo n.º 38
0
Archivo: lisa.py Proyecto: byackee/LISA
# Creating the web stuff
resource_wsgi = wsgi.WSGIResource(reactor, tps.pool, WSGIHandler())
root = libs.Root(resource_wsgi)
staticrsrc = static.File(os.path.normpath(os.path.join(os.path.abspath("."), "web/weblisa/static")))
root.putChild("static", staticrsrc)

# Create the websocket
if configuration['enable_secure_mode']:
    socketfactory = WebSocketServerFactory("wss://" + configuration['lisa_url'] + ":" +
                                           str(configuration['lisa_web_port_ssl']),debug=False)
else:
    socketfactory = WebSocketServerFactory("ws://" + configuration['lisa_url'] + ":" +
                                           str(configuration['lisa_web_port']),debug=False)

socketfactory.protocol = libs.WebSocketProtocol
socketfactory.protocol.configuration, socketfactory.protocol.dir_path = configuration, dir_path
socketresource = WebSocketResource(socketfactory)
root.putChild("websocket", socketresource)

# Configuring servers to launch
if configuration['enable_secure_mode'] or configuration['enable_unsecure_mode']:
    if configuration['enable_secure_mode']:
        SSLContextFactoryEngine = ssl.DefaultOpenSSLContextFactory(
            os.path.normpath(dir_path + '/' + 'configuration/ssl/server.key'),
            os.path.normpath(dir_path + '/' + 'configuration/ssl/server.crt')
        )
        SSLContextFactoryWeb = ssl.DefaultOpenSSLContextFactory(
            os.path.normpath(dir_path + '/' + 'configuration/ssl/server.key'),
            os.path.normpath(dir_path + '/' + 'configuration/ssl/server.crt')
        )
Ejemplo n.º 39
0
            self.closeConnection('%02.f' % RESULT_FILE_TOO_LARGE)
            return
        elif length == self.maxFramePayloadSize:
            error_code = None
            try:
                result_tlv = self._handler.handle_upload(self._file_content)
            except FileHashError:
                error_code = RESULT_HASH_ERROR
            except Exception:
                log.error(traceback.format_exc())
                error_code = RESULT_FS_ERROR
            if error_code:
                self.closeConnection('%02.f' % error_code)
                return
            result = '%02.f' % RESULT_UPLOAD_SUCCESS
            result += self.unformat_tlv(result_tlv)
            self.closeConnection(result)


if __name__ == '__main__':
    # log.startLogging(sys.stdout)
    '''
    factory_echo = WebSocketServerFactory("ws://localhost:9000", debug=settings.DEBUG)
    factory_echo.protocol = EchoServerProtocol # UploadFileProtocal
    listenWS(factory_echo)'''
    factory_upload = WebSocketServerFactory("ws://localhost:9001",
                                            debug=settings.DEBUG)
    factory_upload.protocol = UploadFileProtocal
    listenWS(factory_upload)
    reactor.run()

class FrameBasedHashServerProtocol(WebSocketServerProtocol):
   """
   Frame-based WebSockets server that computes a running SHA-256 for message data
   received. It will respond after every frame received with the digest computed
   up to that point. It can receive messages of unlimited number of frames.
   Digest is reset upon new message.
   """

   def onMessageBegin(self, opcode):
      WebSocketServerProtocol.onMessageBegin(self, opcode)
      self.sha256 = hashlib.sha256()

   def onMessageFrame(self, payload, reserved):
      data = ''.join(payload)
      self.sha256.update(data)
      digest = self.sha256.hexdigest()
      self.sendMessage(digest)
      print "Sent digest for frame: %s" % digest

   def onMessageEnd(self):
      pass


if __name__ == '__main__':
   factory = WebSocketServerFactory("ws://localhost:9000")
   factory.protocol = FrameBasedHashServerProtocol
   listenWS(factory)
   reactor.run()
Ejemplo n.º 41
0
      user = User(username=user_name,password=password,email="",role=400,active=1)
      db.session.add(user)
      db.session.commit()
   except IntegrityError:
      return "IntegrityError"
   except:return "ServerError"
   return "true"
@app.route('/scriptcam.lic')
def static_from_root():
   return redirect('/static/ScriptCam/scriptcam.lic')

##
## create a Twisted Web resource for our WebSocket server
##
msgFactory = WebSocketServerFactory(IP,debug = debug,debugCodePaths = debug)
msgFactory.protocol = MsgServerProtocol
msgFactory.setProtocolOptions(allowHixie76 = True) # needed if Hixie76 is to be supported
msgResource = WebSocketResource(msgFactory)

imgFactory = WebSocketServerFactory(IP,debug = debug,debugCodePaths = debug)
imgFactory.protocol = ImgServerProtocol
imgFactory.setProtocolOptions(allowHixie76 = True) # needed if Hixie76 is to be supported
imgResource = WebSocketResource(imgFactory)

##
## create a Twisted Web WSGI resource for our Flask server
##
wsgiResource = WSGIResource(reactor, reactor.getThreadPool(), app)

##
## create a root resource serving everything via WSGI/Flask, but
Ejemplo n.º 42
0
        """
        log.msg('Sending message to connections: %s' % data)

        payload = data.encode('utf8')

        # Send message through all connections
        for c in set(cls.connections):
            reactor.callFromThread(cls.sendMessage, c, payload)


# Log to standard output
log.startLogging(sys.stdout)

# The actual web socket
factory = WebSocketServerFactory(u'ws://localhost:9000', debug=False)
factory.protocol = WebSocket

# Initialize readers
r = readers()
valid_reader_index = -1

# Check if any valid readers are connected
for i in range(len(r)):
    for valid_card_reader in VALID_CARD_READERS:
        if str(r[i]).find(valid_card_reader) > -1:
            valid_reader_index = i

            break

# Only start the server if any valid readers are connected
if valid_reader_index >= 0:
Ejemplo n.º 43
0
    def onMessage(self, msg, isBinary):
        if self.service:
            self.service.onMessage(msg, isBinary)

    def onClose(self, wasClean, code, reason):
        if self.service:
            self.service.onClose(wasClean, code, reason)


if __name__ == '__main__':

    if len(sys.argv) > 1 and sys.argv[1] == 'debug':
        log.startLogging(sys.stdout)
        debug = True
    else:
        debug = False

    factory = WebSocketServerFactory("ws://localhost:9000",
                                     debug=debug,
                                     debugCodePaths=debug)

    factory.protocol = ServiceServerProtocol
    factory.setProtocolOptions(allowHixie76=True, failByDrop=False)
    listenWS(factory)

    webdir = File(".")
    web = Site(webdir)
    reactor.listenTCP(8080, web)

    reactor.run()
Ejemplo n.º 44
0
            rest = length - (self.received - self.next)
            self.sha256.update(str(data[:rest]))

            ## send digest
            digest = self.sha256.hexdigest()
            self.sendMessage(digest)
            print "Sent digest for batch %d : %s" % (self.count, digest)

            ## advance to next batch
            self.next += BATCH_SIZE
            self.count += 1

            ## .. and update the digest for the rest
            self.sha256.update(str(data[rest:]))
        else:
            ## otherwise we just update the digest for received data
            self.sha256.update(str(data))

    def onMessageFrameEnd(self):
        pass

    def onMessageEnd(self):
        pass


if __name__ == '__main__':
    factory = WebSocketServerFactory("ws://localhost:9000")
    factory.protocol = StreamingHashServerProtocol
    listenWS(factory)
    reactor.run()
Ejemplo n.º 45
0
         rest = length - (self.received - self.next)
         self.sha256.update(data[:rest])

         ## send digest
         digest = self.sha256.hexdigest()
         self.sendMessage(digest)
         print "Sent digest for batch %d : %s" % (self.count, digest)

         ## advance to next batch
         self.next += BATCH_SIZE
         self.count += 1

         ## .. and update the digest for the rest
         self.sha256.update(data[rest:])
      else:
         ## otherwise we just update the digest for received data
         self.sha256.update(data)

   def onMessageFrameEnd(self):
      pass

   def onMessageEnd(self):
      pass


if __name__ == '__main__':
   factory = WebSocketServerFactory("ws://localhost:9000")
   factory.protocol = StreamingHashServerProtocol
   listenWS(factory)
   reactor.run()
Ejemplo n.º 46
0
   def onMessage(self, msg, binary):
      self.sendMessage("Echo 2 - " + msg)


if __name__ == '__main__':

   if len(sys.argv) > 1 and sys.argv[1] == 'debug':
      log.startLogging(sys.stdout)
      debug = True
   else:
      debug = False

   factory1 = WebSocketServerFactory("ws://localhost:9000",
                                     debug = debug,
                                     debugCodePaths = debug)
   factory1.protocol = Echo1ServerProtocol
   resource1 = WebSocketResource(factory1)

   factory2 = WebSocketServerFactory("ws://localhost:9000",
                                     debug = debug,
                                     debugCodePaths = debug)
   factory2.protocol = Echo2ServerProtocol
   resource2 = WebSocketResource(factory2)

   ## Establish a dummy root resource
   root = Data("", "text/plain")

   ## and our WebSocket servers under different paths ..
   root.putChild("echo1", resource1)
   root.putChild("echo2", resource2)
Ejemplo n.º 47
0
      self.sendMessage(msg, binary)
 
#
# To run the demo:
#
# Open a WebSocket-enabled browser to http://localhost:8080/demo
#   - open the Javascript console to see the echo text
#   - click the [Send] button
#
 
if __name__ == '__main__':
    log.startLogging(sys.stdout)

    # Set up an Autobahn echo server
    ws = WebSocketServerFactory("ws://localhost:8080", debug = True)
    ws.protocol = EchoServerProtocol

    root = resource.Resource()
    root.putChild("demo", DemoResource())
    site = server.Site(root)

    factory = BufferingProxyFactory()
    factory.buffer_Factory = PacketBuffer

    # Route /demo urls to our website
    ExampleDispatcher.prefix1 = "/demo"
    ExampleDispatcher.site1 = site

    # Route "/" to the Autobahn websocket server
    ExampleDispatcher.prefix2 = "/"
    ExampleDispatcher.site2 = ws
Ejemplo n.º 48
0
    def tick_flames():
        traceerr(GAME._flames_process)
        reactor.callLater(FLAME_TICK_TIME, tick_flames)

    def tick_actions():
        traceerr(GAME._actions_process)
        reactor.callLater(ACTION_TICK_TIME, tick_actions)

    def tick_bombs():
        traceerr(GAME._bombs_process)
        reactor.callLater(BOMB_TICK_TIME, tick_bombs)

    factory = WebSocketServerFactory()
    # TODO: choose a more sensible port
    # TODO: add a REST interface to get the port
    factory.port = 9000  # ugh, why do I have to do this twice?
    factory.protocol = GameProtocol
    reactor.listenTCP(interface=hostname, port=9000, factory=factory)

    reactor.listenTCP(factory=server.Site(ServerRoot(None)), interface=hostname, port=port)

    reactor.callWhenRunning(tick_flames)
    reactor.callWhenRunning(tick_actions)
    reactor.callWhenRunning(tick_bombs)

    print "Listening on: http://%s:%d" % (hostname, port)
    print "Admin uid:", ADMIN_UID

    reactor.run()
Ejemplo n.º 49
0
        listenWS
import settings.py
import logger.py

class ServerProtocol(WebSocketServerProtocol):
 
   def onConnect(self, request):
      print("Client connecting: {}".format(request.peer))

   def onOpen(self):
      print("WebSocket connection open.")

   def onMessage(self, payload, isBinary):
      if isBinary:
         print("Binary message received: {} bytes".format(len(payload)))
      else:
         print("Text message received: {}".format(payload.decode('utf8')))
         # Add command parsing

      ## echo back message verbatim
      self.sendMessage(payload, isBinary)

   def onClose(self, wasClean, code, reason):
      print("WebSocket connection closed: {}".format(reason))
 
if __name__ == '__main__':
    factory = WebSocketServerFactory("ws:"+API_URL)
    factory.protocol = ServerProtocol
    listenWS(factory)
    reactor.run()
  
Ejemplo n.º 50
0
        # print 'get file size:', length
        if length > self.maxFramePayloadSize:
            self.closeConnection('%02.f' %RESULT_FILE_TOO_LARGE)
            return
        elif length == self.maxFramePayloadSize:
            error_code = None
            try:
                result_tlv = self._handler.handle_upload(self._file_content)
            except FileHashError:
                error_code = RESULT_HASH_ERROR
            except Exception:
                log.error(traceback.format_exc())
                error_code = RESULT_FS_ERROR
            if error_code:
                self.closeConnection('%02.f' %error_code)
                return
            result = '%02.f' %RESULT_UPLOAD_SUCCESS
            result += self.unformat_tlv(result_tlv)
            self.closeConnection(result)

if __name__ == '__main__':
    # log.startLogging(sys.stdout)
    '''
    factory_echo = WebSocketServerFactory("ws://localhost:9000", debug=settings.DEBUG)
    factory_echo.protocol = EchoServerProtocol # UploadFileProtocal
    listenWS(factory_echo)'''
    factory_upload = WebSocketServerFactory("ws://localhost:9001", debug=settings.DEBUG)
    factory_upload.protocol = UploadFileProtocal
    listenWS(factory_upload)
    reactor.run()
    
Ejemplo n.º 51
0
                               listenWS


class EchoServerProtocol(WebSocketServerProtocol):

   def onMessage(self, msg, binary):
      self.sendMessage(msg, binary)


if __name__ == '__main__':

   if len(sys.argv) > 1 and sys.argv[1] == 'debug':
      log.startLogging(sys.stdout)
      debug = True
   else:
      debug = False

   factory = WebSocketServerFactory("ws://localhost:9000",
                                    debug = debug,
                                    debugCodePaths = debug)

   factory.protocol = EchoServerProtocol
   factory.setProtocolOptions(allowHixie76 = True)
   listenWS(factory)

   webdir = File(".")
   web = Site(webdir)
   reactor.listenTCP(8080, web)

   reactor.run()
Ejemplo n.º 52
0
    stickY = self.state.get("LEFT_STICK_Y")
    if stickX is not None and stickY is not None:
      self.robot.setVelocity(stickX, -stickY)

class UglyProtocol(WebSocketServerProtocol):

  def onGamepadCommand(self, command):
    self.gamepadController.onGamepadState(command)

  def onMessage(self, msg, binary):
    command = json.loads(msg)
    cmd = command.get("cmd")    
    if cmd:
      method = "on" + cmd.capitalize() + "Command"
      try:
        getattr(self, method)(command)
      except AttributeError:
        print("Unknown command received: " + cmd.capitalize)
 
  def onOpen(self):
    self.robot = UglyRobot()
    self.gamepadController = UglyGamepadController(self.robot)

if __name__ == '__main__':
  url = "ws://0.0.0.0:9000"
  factory = WebSocketServerFactory(url)
  factory.protocol = UglyProtocol
  listenWS(factory)
  print("UglyRobot server listening on " + url)
  reactor.run()
Ejemplo n.º 53
0
#
# This is the server runtime. It creates a server that listens on port configured in config.
#

from twisted.internet import reactor
from autobahn.websocket import WebSocketServerFactory, listenWS

from server import VectorServerProtocol

import config

factory = WebSocketServerFactory(config.SERVER_ADDRESS)
factory.protocol = VectorServerProtocol
listenWS(factory)
reactor.run()
Ejemplo n.º 54
0
def start_server():
    factory = WebSocketServerFactory("ws://127.0.0.1:9000")
    factory.protocol = EchoServerProtocol
    factory.setProtocolOptions(allowHixie76=True)
    listenWS(factory)