How to use the websockets.serve function in websockets

To help you get started, we’ve selected a few websockets examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github eerimoq / asn1tools / tests / js_source / server.py View on Github external
def main():
    c_source = asn1tools.compile_files([
        'asn1/c_source.asn',
        'asn1/programming_types.asn'
    ], 'oer')

    start_server = websockets.serve(
        functools.partial(echo, c_source=c_source),
        'localhost',
        8765)

    print('Listening for websocket clients on localhost:8765...')

    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
github monolithworks / trueseeing / api / trueseeing / api / server.py View on Github external
parser = configparser.ConfigParser()
    parser.read(configfile)
    TS2Key.PERSONALITY = base64.b64decode(parser['trueseeingd']['personality'])

    logging.basicConfig(level=log_level, format="%(msg)s")

    if not foreground:
        if os.fork():
            sys.exit(0)
        else:
            devnull = os.open(os.devnull, os.O_RDWR)
            os.dup2(devnull, 0)
            os.dup2(devnull, 1)
            os.dup2(devnull, 2)

    start_server = websockets.serve(entry, listen_at['host'], listen_at['port'])
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
github kylewm / woodwind / woodwind / websocket_server.py View on Github external
@asyncio.coroutine
def handle_subscription(websocket, path):
    topic = yield from websocket.recv()
    redis = yield from asyncio_redis.Connection.create()
    ps = yield from redis.start_subscribe()
    yield from ps.subscribe(['woodwind_notify:' + topic])
    while True:
        message = yield from ps.next_published()
        if not websocket.open:
            break
        yield from websocket.send(message.value)
    redis.close()


asyncio.get_event_loop().run_until_complete(
    websockets.serve(handle_subscription, 'localhost', 8077))
asyncio.get_event_loop().run_forever()
github sjdv1982 / seamless / seamless-OLD / websocketserver.py View on Github external
async def start_async(self):
        import websockets
        if self._server is not None:
            return
        port = self.DEFAULT_PORT
        while 1:
            try:
                server = await websockets.serve(self._serve, self.address, port)
                break
            except OSError:
                port += 1
        print("Opened the seamless websocketserver at port {0}".format(port))
        self._server = server
        self.port = port
github iotile / coretools / transport_plugins / websocket / iotile_transport_websocket / generic / async_server.py View on Github external
async def _run_server_task(self, started_signal):
        """Create a BackgroundTask to manage the server.

        This allows subclasess to attach their server related tasks as
        subtasks that are properly cleaned up when this parent task is
        stopped and not require them all to overload start() and stop()
        to perform this action.
        """

        try:
            server = await websockets.serve(self._manage_connection, self.host, self.port)
            port = server.sockets[0].getsockname()[1]
            started_signal.set_result(port)
        except Exception as err:
            self._logger.exception("Error starting server on host %s, port %s", self.host, self.port)
            started_signal.set_exception(err)
            return

        try:
            while True:
                await asyncio.sleep(1)
        except asyncio.CancelledError:
            self._logger.info("Stopping server due to stop() command")
        finally:
            server.close()
            await server.wait_closed()
github streamlit / streamlit / tiny_notebook.py View on Github external
def launch_server(loop):
    """Launches the server and runs an asyncio loop forever."""
    asyncio.set_event_loop(loop)
    start_server = websockets.serve(handle_connection, '', WEBSOCKET_PORT)
    try:
        loop.run_until_complete(start_server)
        print('Starting the server loop...')
        loop.run_forever()
    finally:
        print('About to close the loop.')
        loop.close()
github iov-one / iov-core / scripts / socketserver / echo.py View on Github external
parser.add_argument("--port",
        help="Port to listen on",
        type=int,
        default=4000)
    parser.add_argument("--delay",
        help="Time in seconds that a connection will be delayed before establishing it",
        type=int,
        default=0)
    args = parser.parse_args()

    def delaying_process_request(path, request_headers):
        time.sleep(args.delay)
        return None

    log("Starting server at {}:{}".format(HOST, args.port))
    server = websockets.serve(connection_handler, HOST, args.port, process_request=delaying_process_request)
    log("Running now.")

    asyncio.get_event_loop().run_until_complete(server)
    asyncio.get_event_loop().run_forever()
github kawasaki / bluepy-scratch-link / scratch_link.py View on Github external
localhost_cer = pathlib.Path(__file__).with_name("scratch-device-manager.cer")
localhost_key = pathlib.Path(__file__).with_name("scratch-device-manager.key")
ssl_context.load_cert_chain(localhost_cer, localhost_key)
sessionTypes = { '/scratch/ble': BLESession, '/scratch/bt': BTSession }

async def ws_handler(websocket, path):
    try:
        logger.info(f"Start session for web socket path: {path}")
        loop = asyncio.get_event_loop()
        session = sessionTypes[path](websocket, loop)
        await session.handle()
    except Exception as e:
        logger.error(f"Failure in session for web socket path: {path}")
        logger.error(e)

start_server = websockets.serve(
    ws_handler, "device-manager.scratch.mit.edu", 20110, ssl=ssl_context
)

def stack_trace():
    print("in stack_trace")
    code = []
    for threadId, stack in sys._current_frames().items():
        code.append("\n# ThreadID: %s" % threadId)
        for filename, lineno, name, line in traceback.extract_stack(stack):
            code.append('File: "%s", line %d, in %s' % (filename,
                                                    lineno, name))
            if line:
                code.append("  %s" % (line.strip()))

    for line in code:
         print(line)
github pandysong / ghost-text.vim / python3 / websocket_server.py View on Github external
def start(self, host='localhost', port='8765'):
        start_server = websockets.serve(
            self.ws_manager.handler(), host, port)
        self.server = self.loop.run_until_complete(start_server)
        ghost_log.p('websockets server listen on {}:{}'.format(host, port))
github OpenMined / PySyft / syft / workers / websocket.py View on Github external
def start(self):
        start_server = websockets.serve(self.handler, self.host, self.port)
        asyncio.get_event_loop().run_until_complete(start_server)
        asyncio.get_event_loop().run_forever()