Python autobahn.twisted.websocket.WebSocketServerFactory() Examples

The following are 7 code examples of autobahn.twisted.websocket.WebSocketServerFactory(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module autobahn.twisted.websocket , or try the search function .
Example #1
Source File: botaction_recorder.py    From universe with MIT License 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description=None)
    parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help='Set verbosity.')
    parser.add_argument('-l', '--listen-address', default='127.0.0.1:15896', help='Address to listen on')
    parser.add_argument('-o', '--botaction-logfile', default='/tmp/demo/botactions.jsonl', help='Filename for timestamped log of bot actions.')
    args = parser.parse_args()

    BotactionRecordingServer.logfile_path = args.botaction_logfile

    if args.verbosity == 0:
        logger.setLevel(logging.INFO)
    elif args.verbosity >= 1:
        logger.setLevel(logging.DEBUG)

    factory = websocket.WebSocketServerFactory()
    factory.protocol = BotactionRecordingServer

    host, port = args.listen_address.split(':')
    port = int(port)
    logger.info('Listening on %s:%s', host, port)
    reactor.listenTCP(port, factory)
    reactor.run()
    return 0 
Example #2
Source File: reward_recorder.py    From universe with MIT License 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description=None)
    parser.add_argument('-v', '--verbose', action='count', dest='verbosity', default=0, help='Set verbosity.')
    parser.add_argument('-l', '--listen-address', default='0.0.0.0:15898', help='Address to listen on')
    parser.add_argument('-s', '--rewarder-address', default='127.0.0.1:15900', help='Address of the reward server to run on.')
    parser.add_argument('-d', '--logfile-dir', default=None, help='Base directory to write logs for each connection')
    args = parser.parse_args()

    if args.verbosity == 0:
        logger.setLevel(logging.INFO)
    elif args.verbosity >= 1:
        logger.setLevel(logging.DEBUG)

    factory = websocket.WebSocketServerFactory()
    factory.protocol = reward_proxy_server.RewardProxyServer
    factory.rewarder_address = args.rewarder_address
    factory.logfile_dir = args.logfile_dir
    factory.setProtocolOptions(maxConnections=1)  # We only write reward logs to one place, so only allow one connection

    host, port = args.listen_address.split(':')
    port = int(port)
    logger.info('Listening on %s:%s', host, port)
    reactor.listenTCP(port, factory)
    reactor.run()
    return 0 
Example #3
Source File: websocket.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def startService(self):

        factory = WebSocketServerFactory(u"ws://127.0.0.1:%d" % self.port,
                                         debug=self.debug)
        factory.protocol = DispatcherProtocol
        factory.protocol.dispatcher = CommandDispatcher(self._core)

        # 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('leap.bitmask.core', 'web'))
        root = File(webdir)

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

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

        self.site = site
        self.factory = factory

        self.listener = reactor.listenTCP(self.port, site) 
Example #4
Source File: remote.py    From universe with MIT License 5 votes vote down vote up
def listen(self, port=15900):
        logger.info('Starting Rewarder on port=%s', port)
        factory = websocket.WebSocketServerFactory()
        factory.agent_conn = self
        factory.protocol = RewarderProtocol

        reactor.callFromThread(reactor.listenTCP, port, factory) 
Example #5
Source File: server_websocket.py    From magic-wormhole-mailbox-server with MIT License 5 votes vote down vote up
def __init__(self, url, server):
        websocket.WebSocketServerFactory.__init__(self, url)
        self.setProtocolOptions(autoPingInterval=60, autoPingTimeout=600)
        self.server = server
        self.reactor = reactor # for tests to control 
Example #6
Source File: test_api_end_to_end.py    From python-api with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    market_factory = WebSocketServerFactory('ws://localhost:8080/market_stream')
    user_factory = WebSocketServerFactory('ws://localhost:8080/user_stream')
    market_factory.protocol = MarketStreamServerProtocol
    user_factory.protocol = UserStreamServerProtocol
    market_factory.startFactory()
    user_factory.startFactory()
    root = Data('', 'text/plain')
    root.putChild(b'market_stream', WebSocketResource(market_factory))
    root.putChild(b'user_stream', WebSocketResource(user_factory))
    site = Site(root)
    reactor.listenTCP(8080, site)
    def run_server():
      reactor.run(installSignalHandlers=False)
    Thread(target=run_server).start() 
Example #7
Source File: websocket.py    From pajbot with MIT License 4 votes vote down vote up
def __init__(self, manager, port, secure=False, key_path=None, crt_path=None, unix_socket_path=None):
        self.manager = manager
        from twisted.internet import reactor, ssl

        from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol

        class MyServerProtocol(WebSocketServerProtocol):
            def onConnect(self, request):
                # log.info(self.factory)
                # log.info('Client connecting: {0}'.format(request.peer))
                pass

            def onOpen(self):
                log.info("WebSocket connection open")
                WebSocketServer.clients.append(self)

            def onMessage(self, payload, isBinary):
                if isBinary:
                    log.info(f"Binary message received: {len(payload)} bytes")
                else:
                    log.info(f"Text message received: {payload.decode('utf8')}")

            def onClose(self, wasClean, code, reason):
                log.info(f"WebSocket connection closed: {reason}")
                try:
                    WebSocketServer.clients.remove(self)
                except:
                    pass

        factory = WebSocketServerFactory()
        factory.setProtocolOptions(autoPingInterval=15, autoPingTimeout=5)
        factory.protocol = MyServerProtocol

        def reactor_run(reactor, factory, port, context_factory=None, unix_socket_path=None):
            if unix_socket_path:
                sock_file = Path(unix_socket_path)
                if sock_file.exists():
                    sock_file.unlink()
                reactor.listenUNIX(unix_socket_path, factory)
            else:
                if context_factory:
                    log.info("wss secure")
                    reactor.listenSSL(port, factory, context_factory)
                else:
                    log.info("ws unsecure")
                    reactor.listenTCP(port, factory)
            reactor.run(installSignalHandlers=0)

        if secure:
            context_factory = ssl.DefaultOpenSSLContextFactory(key_path, crt_path)
        else:
            context_factory = None

        reactor_thread = threading.Thread(
            target=reactor_run, args=(reactor, factory, port, context_factory, unix_socket_path), name="WebSocketThread"
        )
        reactor_thread.daemon = True
        reactor_thread.start()