Exemplo n.º 1
0
def start() -> None:
    log(f"Starting websocket server (controller.py) at {IP}:{PORT}")

    server = serve(handler, IP, PORT)

    asyncio.get_event_loop().run_until_complete(server)
    asyncio.get_event_loop().run_forever()
Exemplo n.º 2
0
 def start(self):
     """Start the websocket server"""
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
     server = serve(self.handler, 'localhost', 8080)
     self.server = self.loop.run_until_complete(server)
     self.loop.run_forever()
Exemplo n.º 3
0
 async def run_forever(self):
     """
         Start to serve the server forever.
     """
     print("Starting websocket server...")
     async with server.serve(self.handler, "127.0.0.1", self.port):
         print("Started server")
         await asyncio.Future()
Exemplo n.º 4
0
def main():
    config = get_config()

    loop = zmq.asyncio.ZMQEventLoop()
    asyncio.set_event_loop(loop)

    serve = server.serve(partial(handle_websocket, config=config),
                         host=config['host'],
                         port=config['websocket']['port'])

    asyncio.ensure_future(pub_server(config))
    asyncio.ensure_future(serve)
    loop.run_forever()
Exemplo n.º 5
0
def main():
    config = get_config()

    loop = zmq.asyncio.ZMQEventLoop()
    asyncio.set_event_loop(loop)

    serve = server.serve(
        partial(handle_websocket, config=config),
        host=config['host'],
        port=config['websocket']['port']
    )

    asyncio.ensure_future(pub_server(config))
    asyncio.ensure_future(serve)
    loop.run_forever()
Exemplo n.º 6
0
def experiment_server(port=9130):
    """Starts a websocket server to listen for experiment requests.

    This function is used to initiate an experiment server. Rather
    than specify the parameters via the command-line, this mode waits
    for PLACE experiment configuration to arrive via a websocket.

    Once this server is started, it will need to be killed via ctrl-c or
    similar.

    """
    def ask_exit():
        """Signal handler to catch ctrl-c (SIGINT) or SIGTERM"""
        loop.stop()

    async def experiment_socket(websocket, _):
        """Creates an asyncronous websocket to listen for experiments."""
        print("...sending connection message...")
        await websocket.send('<VERS>' + __version__)
        # get experiment configuration from the webapp
        try:
            print("...waiting for experiment configuration data...")
            sys.stdout.flush()
            json_string = await websocket.recv()
        except ConnectionClosed as err:
            print("...connection closed: " + str(err))
        else:
            print("...starting experiment...")
            web_main(json_string)
            print("...experiment complete.")

    print("PLACE " + __version__ + " | Author: Paul Freeman | 2018")
    print(
        "Originally created by: Jami L Johnson, Henrik tom Wörden, and Kasper van Wijk"
    )
    print("Starting websockets server on port {}".format(port))
    loop = get_event_loop()
    # set up signal handlers
    for signame in ('SIGINT', 'SIGTERM'):
        loop.add_signal_handler(getattr(signal, signame), ask_exit)
    coroutine = serve(experiment_socket, 'localhost', port)
    # run websocket server
    server = loop.run_until_complete(coroutine)
    loop.run_forever()
    # cleanup
    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.close()
Exemplo n.º 7
0
async def mock_ws(host, port, done):
    events = []

    async def process_request(path, request_headers):
        if path == "/healthcheck":
            return HTTPStatus.OK, {}, b""

    async def _handler(websocket, path):
        while True:
            event = await websocket.recv()
            events.append(event)
            cloud_event = from_json(event)
            if cloud_event[
                    "type"] == "com.equinor.ert.forward_model_stage.success":
                break

    async with serve(_handler, host, port, process_request=process_request):
        await done
    return events
Exemplo n.º 8
0
    def run(self):
        try:
            self.loop = asyncio.get_event_loop()
        except:
            self.loop = asyncio.new_event_loop()
            asyncio.set_event_loop(self.loop)
            logging.debug("Loop created")

        start_server = serve(self.handler,
                             self.bindingAddress,
                             self.port,
                             loop=self.loop)

        self.server = self.loop.run_until_complete(start_server)
        logging.info("WS server ready")
        if self.browserLock:
            self.browserLock.release()
        try:
            self.loop.run_forever()
        finally:
            self.loop.run_until_complete(self.server.wait_closed())
            logging.info("WS server off")
Exemplo n.º 9
0
    def __init__(self):
        self._username = "".join(
            random.choice(string.ascii_letters) for _ in range(6))
        self._password = "".join(
            random.choice(string.ascii_letters) for _ in range(6))
        self._api_key = "".join(
            random.choice(string.ascii_letters) for _ in range(6))
        self._method_handlers = {}

        self.register_method_handler(
            "auth.login",
            lambda u, p: u == self.username and p == self.password,
        )

        self.register_method_handler(
            "auth.login_with_api_key",
            lambda t: t == self.api_key,
        )

        self._subscription_queue = asyncio.Queue()

        self._serve_handle = serve(self._handle_messages, "localhost", 8000)
        asyncio.get_event_loop().run_until_complete(self._serve_handle)
    def __init__(self, in_q, out_q, state):

        self.channel_to_q = in_q
        self.webstudio_to_q = out_q

        process_title = "Websockets Servr"
        setproctitle(process_title)
        current_process().name = process_title

        self.logger = LoggingManager("Websockets")
        self.server_name = state.get()["server_name"]

        self.websocket_server = serve(self.websocket_handler,
                                      state.get()["host"],
                                      state.get()["ws_port"])

        asyncio.get_event_loop().run_until_complete(self.websocket_server)
        asyncio.get_event_loop().run_until_complete(self.handle_to_webstudio())

        try:
            asyncio.get_event_loop().run_forever()
        except Exception:
            # Sever died somehow, just quit out.
            self.quit()
Exemplo n.º 11
0
 def __init__(self, port):
     self.port = port
     self.start_server = server.serve(self.handler, "127.0.0.1", self.port)
Exemplo n.º 12
0
async def main():
    async with serve(counter, "localhost", 6789):
        await asyncio.Future()  # run forever
Exemplo n.º 13
0
Arquivo: app.py Projeto: jdoble97/chat
            for client in server_ws.get_clients()
        ])


async def handle_connection(ws, path):
    '''
    Se ejecutará esta función cada vez que se conecte un nuevo cliente
    '''
    await register_client(ws)
    await notify_new_client(ws)
    try:
        async for message in ws:
            print(f'Mensaje recibido de {server_ws.get_client(ws)}: {message}')
            for client in server_ws.get_clients():
                if client is not ws:
                    await operations_ws.send_msg(client, message,
                                                 server_ws.get_client(ws))
    finally:
        await unregister_client(ws)


if __name__ == '__main__':
    server = server.serve(handle_connection, ADDRESS, PORT)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(server)
    print(f'Serve in {ADDRESS}:{PORT}')
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        print('It is stopped the server')
Exemplo n.º 14
0
                    await self.error_reply(NOT_FOUND)
                except (TypeError, IndexError):
                    import traceback
                    print(traceback.format_exc())
                    await self.error_reply(INCORRECT_PARAMETERS)
        except GraphException as error:
            await self.error_reply(error.message)


async def ws_handler(websocket, path):
    handler = WebSocketHandler(websocket)
    async for command in websocket:
        await handler.handle(command)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        usage='Usage: python3 -m grapher.core.server --port PORT_NUMBER',
        description=(
            'Runs a Grapher server on a specified port or 9999 if port number was not provided.'
        )
    )
    parser.add_argument(
        '-p', '--port', dest='port', type=int
    )
    args = parser.parse_args()

    port = args.port or PORT
    asyncio.get_event_loop().run_until_complete(serve(ws_handler, HOST, port))
    asyncio.get_event_loop().run_forever()