def __init__(self, url):
        WebSocketServerFactory.__init__(self, url)
        self.clients = []
        self.tickGap = 5
        self.tickSetup()

        listenWS(self)
Пример #2
0
    def __init__(self, url, debug=False, ident=None):
        if ident is not None:
            server = ident
        else:
            server = "AutobahnPython/%s" % autobahn.version
        WebSocketServerFactory.__init__(self,
                                        url,
                                        debug=debug,
                                        debugCodePaths=debug,
                                        server=server)
        self.setProtocolOptions(failByDrop=False)  # spec conformance

        #self.setProtocolOptions(failByDrop = True) # needed for streaming mode
        #self.setProtocolOptions(utf8validateIncoming = False)

        ## enable permessage-XXX compression extensions
        ##
        def accept(offers):
            for offer in offers:
                if isinstance(offer, PerMessageDeflateOffer):
                    return PerMessageDeflateOfferAccept(offer)

                elif isinstance(offer, PerMessageBzip2Offer):
                    return PerMessageBzip2OfferAccept(offer)

                elif isinstance(offer, PerMessageSnappyOffer):
                    return PerMessageSnappyOfferAccept(offer)

        self.setProtocolOptions(perMessageCompressionAccept=accept)
Пример #3
0
   def __init__(self, spec, debug = False):

      WebSocketServerFactory.__init__(self, debug = debug, debugCodePaths = debug)
      FuzzingFactory.__init__(self, spec.get("outdir", "./reports/clients/"))

      # needed for wire log / stats
      self.logOctets = True
      self.logFrames = True

      ## WebSocket session parameters
      ##
      self.setSessionParameters(url = spec["url"],
                                protocols = spec.get("protocols", []),
                                server = "AutobahnTestSuite/%s-%s" % (autobahntestsuite.version, autobahn.version))

      ## WebSocket protocol options
      ##
      self.setProtocolOptions(**spec.get("options", {}))

      self.spec = spec

      self.CaseSet = CaseSet(CaseBasename, Cases, CaseCategories, CaseSubCategories)

      self.specCases = self.CaseSet.parseSpecCases(self.spec)
      self.specExcludeAgentCases = self.CaseSet.parseExcludeAgentCases(self.spec)
      print "Autobahn WebSockets %s/%s Fuzzing Server (Port %d%s)" % (autobahntestsuite.version, autobahn.version, self.port, ' TLS' if self.isSecure else '')
      print "Ok, will run %d test cases for any clients connecting" % len(self.specCases)
      print "Cases = %s" % str(self.specCases)
Пример #4
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)
Пример #5
0
	def __init__(self, *args, **kwargs):
		# pop api parameter off
		self.api = kwargs.pop('api', None)
		self.allow_ga = kwargs.pop('allow_ga', None)
		self.deny_ga = kwargs.pop('deny_ga', None)
		
		kwargs['server'] = 'saged/0.1.0 (libcbus)'
		
		WebSocketServerFactory.__init__(self, *args, **kwargs)

		
		
		self.clients = []
		
		# wire up events so we can handle events from cdbusd and populate to clients
		
		for n, m in (
			('on_lighting_group_on', self.on_lighting_group_on),
			('on_lighting_group_off', self.on_lighting_group_off),
			('on_lighting_group_ramp', self.on_lighting_group_ramp)
		):
			api.connect_to_signal(
				handler_function=m,
				signal_name=n
			)
Пример #6
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')
Пример #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()
Пример #8
0
 def startFactory(self):
     WebSocketServerFactory.startFactory(self)
     self.setOptionsFromConfig()
     log.msg(
         "EchoWebSocketFactory started [speaking WebSocket versions %s]" %
         self.versions)
     self.publishStats()
Пример #9
0
 def __init__(self, protocolCls, manager, url):
     """ Initialize the Factory.
     """
     WebSocketServerFactory.__init__(self, url)
     
     self._protocolCls = protocolCls
     self._manager = manager
    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)
Пример #11
0
    def __init__(self, url):
        WebSocketServerFactory.__init__(self, url)
        self.clients = []
        self.tickGap = 5
        self.tickSetup()

        listenWS(self)
Пример #12
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()
Пример #13
0
 def __init__(self, url, debug = False, ident = None):
    if ident is not None:
       server = ident
    else:
       server = "AutobahnPython/%s" % autobahn.version
    WebSocketServerFactory.__init__(self, url, debug = debug, debugCodePaths = debug, server = server)
    self.setProtocolOptions(failByDrop = False) # spec conformance
Пример #14
0
  def __init__(self, udp_port, nick, prefix, chatroom, url = None, protocols = [], debug = False, debugCodePaths = False):
    '''
    Args:
      udp_port (int) : The udp port to listen for WebRTC traffice.
      nick (str) : The nickname for the local user.
      prefix (str) : The prefix for the local user.
      chatroom (str) : The chatroom to join.

    Kwargs:
      url : The url for websocket server
      And other default kwargs of WebSocketServerFactory.

    A roster for the chatroom is maintained here.
    CcnxSocket created for PeetsMessages propagation if NDN.
    '''
    # super can only work with new style classes which inherits from object
    # apparently WebSocketServerFactory is old style class
    WebSocketServerFactory.__init__(self, url = url, protocols = protocols, debug = debug, debugCodePaths = debugCodePaths)
    self.handlers = {'join_room' : self.handle_join, 'send_ice_candidate' : self.handle_ice_candidate, 'send_offer' : self.handle_offer, 'media_ready' : self.handle_media_ready, 'chat_msg': self.handle_chat}
    # keep the list of local clients, first, we deal with the case where there is only one local client
    self.client = None
    # keep the list of remote users
    self.roster = None
    self.listen_port = udp_port
    self.__class__.__logger.debug('UDP-PORT=%s', str(udp_port))
    self.ccnx_socket = CcnxSocket()
    self.ccnx_socket.start()
    self.local_status_callback = lambda status: 0
    self.nick = nick
    self.prefix = prefix
    self.chatroom = chatroom
Пример #15
0
    def __init__(self, url):

        WebSocketServerFactory.__init__(self, url)

        self.clients = []
        self.client_state = {}
        self.tick()
Пример #16
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')
Пример #17
0
 def __init__(self, url, debug=False, debugCodePaths=False):
     WebSocketServerFactory.__init__(self, url, debug=debug, debugCodePaths=debugCodePaths)
     self.clients = []
     self.sensorReadings = deque([])
     self.averageReading = 0
     self.oldAverageReading = 0
     self.tickcount = 0
     self.tick()
Пример #18
0
    def __init__(self, url, geoip_db, geoip_update_interval, lang, project, *a,
                 **kw):
        WebSocketServerFactory.__init__(self, url, *a, **kw)
        self.clients = set()
        self.tickcount = 0

        start_monitor(self, geoip_db, geoip_update_interval, lang,
                      project)  # blargh
Пример #19
0
    def __init__(self, url, geoip_db, geoip_update_interval,
                 lang, project, *a, **kw):
        WebSocketServerFactory.__init__(self, url, *a, **kw)
        self.clients = set()
        self.tickcount = 0

        start_monitor(self, geoip_db, geoip_update_interval,
                      lang, project)  # blargh
Пример #20
0
 def __init__(self, url, debug=False, debugCodePaths=False):
     WebSocketServerFactory.__init__(self,
                                     url,
                                     debug=debug,
                                     debugCodePaths=debugCodePaths)
     self.clients = []
     self.tickcount = 0
     start_monitor(self)
Пример #21
0
 def __init__(self, *args, **kwargs):
     self.username = kwargs.pop('username')
     self.password = kwargs.pop('password')
     self.proxy_host = kwargs.pop('proxy_host', None)
     self.proxy_port = kwargs.pop('proxy_port', 8080)
     self.clients = set()
     WebSocketServerFactory.__init__(self, *args, **kwargs)
     self.initialize()
Пример #22
0
 def __init__(self, url, debug=False, debugCodePaths=False):
     WebSocketServerFactory.__init__(self,
                                     url,
                                     debug=debug,
                                     debugCodePaths=debugCodePaths)
     self.clients = []
     self.tickcount = 0
     self.tick()
Пример #23
0
 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()
Пример #24
0
 def __init__(self, url, debug = False, debugCodePaths = False):
    WebSocketServerFactory.__init__(self, url, debug = debug, debugCodePaths = debugCodePaths)
    self.clients = []
    self.posdict = {}
    self.statedict = {}
    self.randvals = []
    self.tickcount = 0
    self.allready = True
    self.tick()
Пример #25
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')
Пример #26
0
def main():

   log.startLogging(sys.stdout)

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

   reactor.run()
Пример #27
0
 def __init__(self, url, monitor, config, dev_mode,
              debug = False, debugCodePaths = False):
     WebSocketServerFactory.__init__(self, url, debug = debug,
                                     debugCodePaths = debugCodePaths)
     self.config = config
     self.dev_mode = dev_mode
     self.msg_queue = Queue.Queue(maxsize=200)
     self.producers = []
     self.monitor = monitor
     print "in server: properly exiting server factory constructor... "
Пример #28
0
	def run ( self ):
			log.startLogging(sys.stdout)

			factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
			factory.protocol = PushServerProtocol
			listenWS(factory)
			
			reactor.run()
			
			
			
Пример #29
0
 def __init__(self, url, debug=False, debugCodePaths=False):
     WebSocketServerFactory.__init__(self,
                                     url,
                                     debug=debug,
                                     debugCodePaths=debugCodePaths)
     self.clients = []
     self.sensorReadings = deque([])
     self.averageReading = 0
     self.oldAverageReading = 0
     self.tickcount = 0
     self.tick()
	def __init__(self, url):
		WebSocketServerFactory.__init__(self, url)
		self.clients = []
		self.tick()

		#TODO: Move this to threading model and start/stop the thread only when we have registered clients
		# Create a thread as follows
		try:
			thread.start_new_thread(update_ports, (self, ))
		except:
			print "Error: unable to start thread"
Пример #31
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()
Пример #32
0
 def __init__(self, url):
   WebSocketServerFactory.__init__(self, url)
   self.clients = []
   self.tickcount = 0
   self.maxWidth = 700
   self.maxHeight = 500
   self.leftHandPosition = [0, 0]
   self.rightHandPosition= [0, 0]
   self.leftHandState = "O"
   self.rightHandState = "O"
   self.deltaScale = 5
   self.broadcast("Let's start!")
Пример #33
0
	def __init__(self, host, server, debug):
		WebSocketServerFactory.__init__(self, host, server=server, debug=debug)

		#Used to get a dictionary of all clients currently connected.
		#Key 	- Username as a string
		#Value 	- Client protocol
		self.clients = {}

		#Used to get a dictionary of all channels currently created.
		#Key 	- Channel hash as a string
		#Value 	- Channel or Private Channel object
		self.channels = dict()
Пример #34
0
    def __init__(self, *args, **kwargs):
        WebSocketServerFactory.__init__(self, *args, **kwargs)

        # safari
        self.allowHixie76 = True

        # identify rpi's by their macs
        # identify user by peerstr
        self.rpi_clients = {}
        self.user_client = {}
        # key RPI mac, value list of user clients
        self.rpi_clients_registered_users = {}
Пример #35
0
    def __init__(self, *args, **kwargs):
        WebSocketServerFactory.__init__(self, *args, **kwargs)

        # safari
        self.allowHixie76 = True

        # identify rpi's by their macs
        # identify user by peerstr
        self.rpi_clients = {}
        self.user_client = {}
        # key RPI mac, value list of user clients
        self.rpi_clients_registered_users = {}
Пример #36
0
    def __init__(self, *args, **kwargs):
        self.database = kwargs.pop('database')
        self.config = kwargs.pop('config')

        WebSocketServerFactory.__init__(self, *args, **kwargs)

        self.logger = logging.getLogger(__name__)

        self.connections = {}
        self.stations = {}

        task.LoopingCall(self.fetch_playlist).start(300, now=False)
        task.LoopingCall(self.send_status).start(30)
Пример #37
0
    def __init__(self, url, debug = False, debugCodePaths = False):
        WebSocketServerFactory.__init__(self, url, debug = debug, 
                                        debugCodePaths = debugCodePaths)
        self.qlength = 0
        self.num_msg = 0
        self.throughput = 0.0
        self.latency = 0.0
        self.num_clients = 0
   
        self.old_timestamp = datetime.datetime.utcnow()
        self.old_num_msg = 0

        self.clients = []
Пример #38
0
   def __init__(self, url, dbpool, services, reactor = None):
      WebSocketServerFactory.__init__(self, url, debug = False, debugCodePaths = False, reactor = reactor)

      self.dbpool = dbpool
      self.services = services

      ## reset Echo endpoint stats
      ##
      self.stats = {'wsecho-connections': 0,
                    'wsecho-echos-text-count': 0,
                    'wsecho-echos-text-bytes': 0,
                    'wsecho-echos-binary-count': 0,
                    'wsecho-echos-binary-bytes': 0}
      self.statsChanged = False
Пример #39
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()
Пример #40
0
    def __init__(self, *args, **kwargs):

        WebSocketServerFactory.__init__(self, *args, **kwargs)

        # safari
        self.allowHixie76 = True

        # Identify MSP430's by their macs
        # Identify user by peerstr
        self.msp430_clients = {}
        self.user_client = {}

        # Key MSP430 mac, value list of user clients
        self.msp430_clients_registered_users = {}
Пример #41
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
Пример #42
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()
Пример #43
0
    def __init__(self, url, debug=False, serializers=None, reactor=None):

        if serializers is None:
            serializers = [WampMsgPackSerializer(), WampJsonSerializer()]

        self._serializers = {}
        for ser in serializers:
            self._serializers[ser.SERIALIZER_ID] = ser

        protocols = ["wamp.2.%s" % ser.SERIALIZER_ID for ser in serializers]

        WebSocketServerFactory.__init__(self,
                                        url,
                                        debug=debug,
                                        protocols=protocols,
                                        reactor=reactor)
Пример #44
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')
Пример #45
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)
Пример #46
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')
Пример #47
0
    def __init__(self):
        log.startLogging(sys.stdout)

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

        reactor.run()
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)
Пример #49
0
    def __init__(self, *args, **kwargs):
        # pop api parameter off
        self.api = kwargs.pop('api', None)
        self.allow_ga = kwargs.pop('allow_ga', None)
        self.deny_ga = kwargs.pop('deny_ga', None)

        kwargs['server'] = 'saged/0.1.0 (libcbus)'

        WebSocketServerFactory.__init__(self, *args, **kwargs)

        self.clients = []

        # wire up events so we can handle events from cdbusd and populate to clients

        for n, m in (('on_lighting_group_on', self.on_lighting_group_on),
                     ('on_lighting_group_off', self.on_lighting_group_off),
                     ('on_lighting_group_ramp', self.on_lighting_group_ramp)):
            api.connect_to_signal(handler_function=m, signal_name=n)
Пример #50
0
    def __init__(self, realm, url, **kw):
        """ Initialize the Factory.

            @param realm:       Robot realm implementing necessary callback
                                methods for the protocol.
            @type  realm:       rce.comm.interfaces.IRobotRealm

            @param url:         URL where the WebSocket server factory will
                                listen for connections. For more information
                                refer to the base class:
                                    autobahn.websocket.WebSocketServerFactory
            @type  url:         str

            @param kw:          Additional keyworded arguments will be passed
                                to the __init__ of the base class.
        """
        WebSocketServerFactory.__init__(self, url, **kw)

        self._realm = realm
Пример #51
0
    def __init__(self,
                 port,
                 is_secure=False,
                 debug=False,
                 signing_key=None,
                 signing_id=None,
                 event_handler=GenericEventHandler):
        self.debug = debug
        self.signing_key = signing_key
        self.signing_id = signing_id
        self.protocol = WebsocketServerProtocol
        self.event_handler = event_handler

        if is_secure:
            uri = "wss://0.0.0.0:%d" % port
        else:
            uri = "ws://0.0.0.0:%d" % port

        WebSocketServerFactory.__init__(self, uri)
Пример #52
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')
Пример #53
0
    def __init__(self, url, dbpool, services, reactor=None):
        WebSocketServerFactory.__init__(self,
                                        url,
                                        debug=False,
                                        debugCodePaths=False,
                                        reactor=reactor)

        self.dbpool = dbpool
        self.services = services

        ## reset Echo endpoint stats
        ##
        self.stats = {
            'wsecho-connections': 0,
            'wsecho-echos-text-count': 0,
            'wsecho-echos-text-bytes': 0,
            'wsecho-echos-binary-count': 0,
            'wsecho-echos-binary-bytes': 0
        }
        self.statsChanged = False
Пример #54
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()
    def __init__(self,
                 port,
                 is_secure=False,
                 debug=False,
                 signing_key=None,
                 signing_id=None,
                 event_handler=GenericEventHandler):
        self.debug = debug
        self.signing_key = signing_key
        self.signing_id = signing_id
        self.protocol = WebsocketServerProtocol
        self.event_handler = event_handler

        if is_secure:
            uri = "wss://0.0.0.0:%d" % port
        else:
            uri = "ws://0.0.0.0:%d" % port

        WebSocketServerFactory.__init__(self, uri)


# P.S. There's not Websocket client implementation yet
# P.P.S. And it probably won't be for long time...'
Пример #56
0
 def __init__(self, url):
     WebSocketServerFactory.__init__(self, url)
     self.clients = []
     self.tickcount = 0
     self.tick()
Пример #57
0
 def __init__(self, url):
   WebSocketServerFactory.__init__(self, url)
   self.clients = []