当前位置: 首页>>代码示例>>Python>>正文


Python websocket.WebSocketServerFactory类代码示例

本文整理汇总了Python中autobahn.asyncio.websocket.WebSocketServerFactory的典型用法代码示例。如果您正苦于以下问题:Python WebSocketServerFactory类的具体用法?Python WebSocketServerFactory怎么用?Python WebSocketServerFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了WebSocketServerFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: start_server

def start_server(address, port):
    # see http://autobahn.ws/python/websocket/programming.html

    # accept both string and int, since client has to accept int
    if isinstance(port, int):
        port = str(port)

    global lobby_count
    lobby_count = 0

    composite_address = 'ws://' + address + ':' + port
    info("starting websocket server at {}".format(composite_address), INFO_ID)
    factory = WebSocketServerFactory(composite_address)
    factory.protocol = GameServerProtocol

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop = asyncio.get_event_loop()

    coro = loop.create_server(factory, address, port)
    server = loop.run_until_complete(coro)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        info('cleaning up.', INFO_ID)
    finally:
        server.close()
        loop.close()
开发者ID:andysalerno,项目名称:Towers,代码行数:29,代码来源:ws_server.py

示例2: start_websocket_server

def start_websocket_server():
    """Function to start the websocket server."""
    import asyncio

    if not os.path.exists(LOGFOLDER):
        os.makedirs(LOGFOLDER)
    logging.basicConfig(filename=LOGFOLDER+ "/" + WEBSOCKETLOG,level=LOGLEVEL)
    logging.info("Starting Server")
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    factory = WebSocketServerFactory(
        u"ws://127.0.0.1:" + str(PORT) + "/" + WS_URL, DEBUG)
    factory.protocol = GraphalyzerServerProtocol

    coro = loop.create_server(factory, '0.0.0.0', PORT)
    server = loop.run_until_complete(coro)

    try:
        logging.info("Server started")
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        logging.info("Server shutting down")
        server.close()
        loop.close()
开发者ID:algomez,项目名称:Graphalyzer,代码行数:27,代码来源:app.py

示例3: talker

    def talker(self):
        # In ROS, nodes are uniquely named. If two nodes with the same
        # node are launched, the previous one is kicked off. The
        # anonymous=True flag means that rospy will choose a unique
        # name for our 'talker' node so that multiple talkers can
        # run simultaneously.
        rospy.init_node('blockly_server', anonymous=True)
        rospy.Subscriber("blockly", String, RobotBlocklyBackend.callback)
        CodeStatus.initialize_publisher()
        self.__current_block_publisher = rospy.Publisher('current_block_id', String, queue_size=5)

        rospy.Service('program_is_paused', Trigger, RobotBlocklyBackend.__is_status_paused)
        rospy.Service('program_completed', Empty, RobotBlocklyBackend.__set_status_completed)
        rospy.Service('program_set_current_block_id', SetCurrentBlockId, self.__set_current_block_id)

        factory = WebSocketServerFactory(u"ws://0.0.0.0:9000", debug=False)
        factory.protocol = BlocklyServerProtocol

        loop = asyncio.get_event_loop()
        coro = loop.create_server(factory, '0.0.0.0', 9000)
        server = loop.run_until_complete(coro)
        asyncio.async(RobotBlocklyBackend.wait_until_ros_node_shutdown(loop))

        loop.run_forever()

        print("Closing...")
        server.close()
        loop.run_until_complete(server.wait_closed())
        loop.close()
开发者ID:MKC-Engineering,项目名称:robot_blockly,代码行数:29,代码来源:robot_blockly_backend.py

示例4: talker

def talker():
    # In ROS, nodes are uniquely named. If two nodes with the same
    # node are launched, the previous one is kicked off. The
    # anonymous=True flag means that rospy will choose a unique
    # name for our 'talker' node so that multiple talkers can
    # run simultaneously.
    rospy.init_node("blockly_server", anonymous=True)
    rospy.Subscriber("blockly", String, callback)

    try:
        import asyncio
    except ImportError:
        # Trollius >= 0.3 was renamed
        import trollius as asyncio

    factory = WebSocketServerFactory(u"ws://0.0.0.0:9000", debug=False)
    factory.protocol = BlocklyServerProtocol

    loop = asyncio.get_event_loop()
    coro = loop.create_server(factory, "0.0.0.0", 9000)
    server = loop.run_until_complete(coro)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
        loop.close()
开发者ID:lucasw,项目名称:ros_blockly,代码行数:29,代码来源:blockly_backend.py

示例5: start

	def start(self):
		self.print_debug("start() called... debug = {}".format(self.debug))
		ws = "ws"

		sslcontext = None
		if self.ssl:
			try:
				sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
				sslcontext.load_cert_chain(self.sslcert, self.sslkey)
				self.print_debug("using ssl")
			except Exception as ex:
				sslcontext = None
				self.print_debug("failed to use ssl")
				raise Exception("failed to use ssl: {}".format(ex))

			ws = "wss"	

		ResourceProtocol.server = self

		factory = WebSocketServerFactory(u"{0}://127.0.0.1:{1}".format(ws, self.port))
		factory.protocol = ResourceProtocol

		loop = asyncio.get_event_loop()

		coro = loop.create_server(factory, '', self.port, ssl=sslcontext)
		self.server = loop.run_until_complete(coro)

		self.print_debug("server should be started now")
开发者ID:tripzero,项目名称:python-wss,代码行数:28,代码来源:wssserver.py

示例6: main

def main():
    loop = asyncio.get_event_loop()

    db = loop.run_until_complete(
        aiozmq.rpc.connect_rpc(
            connect=os.environ['DBSERVER_PORT_5000_TCP'],
            translation_table=translation_table,
            timeout=5))

    # Is this good idea to have one connection?
    game = loop.run_until_complete(
        aiozmq.rpc.connect_rpc(
            connect=os.environ['GAME_PORT_5200_TCP'],
            translation_table=translation_table,
            error_table=error_table,
            timeout=5))

    def create_protocol(*args, **kwargs):
        return FrontendHandler(db=db, game=game, *args, **kwargs)

    factory = WebSocketServerFactory(
        url='ws://{}:{}'.format(os.environ['FRONTEND_ADDR'], os.environ['FRONTEND_PORT']),
        loop=loop)
    factory.protocol = create_protocol

    server = loop.run_until_complete(
        loop.create_server(factory, '0.0.0.0', os.environ['FRONTEND_PORT']))

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
        loop.close()
开发者ID:Alerion,项目名称:flatworld,代码行数:35,代码来源:frontend.py

示例7: main

def main(*args):
    """
    Starts the autobahn websockets server, and the receive loop for zeroMQ.
    Defaults for the ZeroMQ address (also overridable via commandline) and the
    websockets server can be overridden in the settings module.
    """
    receive_loop = threading.Thread(target=backend.receive_loop, args=args)
    receive_loop.start()

    factory = WebSocketServerFactory()
    factory.protocol = GraphProtocol

    loop = asyncio.get_event_loop()
    coro = loop.create_server(factory, *settings.WEBSOCKETS_ADDRESS)
    server = loop.run_until_complete(coro)

    try:
        print('Starting the websockets server on %s:%d' % settings.WEBSOCKETS_ADDRESS)
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        print('Closing down the websockets server')
        server.close()
        loop.close()
        sys.exit(0)
开发者ID:mwozniczak,项目名称:netpath-webviewer,代码行数:26,代码来源:websockets_server.py

示例8: startWebsocketServer

def startWebsocketServer():
    print(blue("Websocket server starting up..."))

    try:
        import asyncio
    except ImportError:
        ## Trollius >= 0.3 was renamed
        import trollius as asyncio

    #Asyncio only setups an event loop in the main thread, else we need to
    if threading.current_thread().name != 'MainThread':
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

    factory = WebSocketServerFactory("ws://0.0.0.0:9000", debug = False)
    factory.protocol = TranslatronProtocol

    loop = asyncio.get_event_loop()
    server = loop.create_server(factory, '0.0.0.0', 9000)
    server = loop.run_until_complete(server)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
        loop.close()
开发者ID:ulikoehler,项目名称:Translatron,代码行数:28,代码来源:WebsocketInterface.py

示例9: launch_server

def launch_server():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    factory = WebSocketServerFactory()
    factory.protocol = MyServerProtocol
    coro = loop.create_server(factory, WS_HOST, WS_PORT)
    server = loop.run_until_complete(coro)
    loop.run_forever()
开发者ID:Sellto,项目名称:staffconnection,代码行数:8,代码来源:server.py

示例10: __init__

    def __init__(self, config, *args, **kwargs):
        WebSocketServerFactory.__init__(self, *args, **kwargs)
        for module_name, module_data in config["modules"].items():
            module_import_name = re.sub('(?!^)([A-Z]+)', r'_\1', module_data["type"]).lower()
            self.modules[module_name] = module_data

            module_module = importlib.import_module("modules."+module_import_name)
            module_object = getattr(module_module, module_data["type"])
            self.modules[module_name]["module_object"] = module_object(**module_data)
开发者ID:kommandozentrale,项目名称:kommandozentrale-backend,代码行数:9,代码来源:server.py

示例11: __init__

 def __init__(self, url, config="config.json", *args, **kwargs):
     WebSocketServerFactory.__init__(self, url, *args, **kwargs)
     self.clients = []
     with open(config) as configfile:
         self.config.update(json.load(configfile))
     self.config['switchModule'] = importlib.import_module(self.config['switchModule'])
     for name in self.config["switches"]:
         switch_config = self.config['switches'][name]
         switch_class = switch_config['class']
         initial_data = switch_config
         switch = getattr(self.config["switchModule"], switch_class)(initial_data=initial_data, name=name, factory=self)
         self.config['switches'][name]['class'] = switch
开发者ID:maschinendeck,项目名称:kommandozentrale,代码行数:12,代码来源:server.py

示例12: __init__

	def __init__(self, config_file):
		
		# init before get called
		self.contexts = {}
		self.context_subscriptions = {}
		
		Application.__init__(self, config_file)
		WebSocketServerFactory.__init__(self)
		
		#greenlet.greenlet.__init__(self)
		
		# start the separate tasker process
		IN.tasker.start_the_process()
开发者ID:arvindamirtaa,项目名称:In,代码行数:13,代码来源:ws_application.py

示例13: main

def main():
    factory = WebSocketServerFactory()
    factory.protocol = MyServerProtocol
    loop = asyncio.get_event_loop()
    coro = loop.create_server(factory, '127.0.0.1', 8765)
    server = loop.run_until_complete(coro)
    loop.run_until_complete(asyncio.gather(*[listen_command(),
                                             read_command(),
                                             # write_command(),
                                             print_stats()]))
    loop.run_forever()
    loop.close()
    server.close()
开发者ID:dirtysalt,项目名称:dirtysalt.github.io,代码行数:13,代码来源:test_ws_server.py

示例14: run_liveview_server

def run_liveview_server(liveview_url):

    # set new event loop because there is no default event loop.
    #     asyncio.set_event_loop(asyncio.new_event_loop())

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

    factory.protocol = LiveviewServerProtocol(liveview_url)

    loop = asyncio.get_event_loop()
    coro = loop.create_server(factory, "127.0.0.1", 9000)
    server = loop.run_until_complete(coro)
    loop.run_forever()
    server.close()
    loop.close()
开发者ID:kota65535,项目名称:remote-train,代码行数:15,代码来源:liveview4.py

示例15: main

def main():
    config = load_configuration()
    ServerState.logger = get_logger(config, 'CoreWS')
    address = config.get('CoreWS', 'address', '0.0.0.0')
    port = int(config.get('CoreWS', 'port', '9000'))
    mq_servers = comma_string_to_list(config.get('CoreMQ', 'cluster_nodes', '').split(','))

    ServerState.logger.info('CoreWS Starting up...')
    ws_factory = WebSocketServerFactory('ws://%s:%s/ws' % (address, port))
    ws_factory.protocol = WsProtocol

    loop = asyncio.get_event_loop()
    server_coro = loop.create_server(ws_factory, address, port)
    server = loop.run_until_complete(server_coro)
    ServerState.logger.info('WebSocket Server running')

    mq_factory = CoreMqClientFactory(WsMqClient, mq_servers, loop=loop)

    @asyncio.coroutine
    def connect(*args):
        ServerState.mq_connection = None
        while True:
            yield asyncio.From(mq_factory.connect())
            if not mq_factory.connection:
                ServerState.logger.warn('No CoreMQ servers found. Retrying in 3 seconds...')
                yield asyncio.From(asyncio.sleep(3))
            else:
                conn = mq_factory.connection[1]
                conn.connected_future.add_done_callback(
                    lambda _: conn.begin_replication('%s:%s' % (socket.gethostname(), port))
                )
                ServerState.mq_connection = conn
                break

    mq_factory.lost_connection_callback = connect
    loop.run_until_complete(connect())

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        ServerState.logger.info('Shutting down WebSocket Server...')
        server.close()
        ServerState.logger.info('Shutting down MQ Client...')
        mq_factory.close()
        loop.close()
        ServerState.logger.info('CoreWS is now shut down')
开发者ID:deejross,项目名称:coremq,代码行数:48,代码来源:ws_server.py


注:本文中的autobahn.asyncio.websocket.WebSocketServerFactory类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。