[Python] Problem in specifying a path in a websocket server URL

Discussão em 'Python' iniciado por Stack, Janeiro 2, 2025.

  1. Stack

    Stack Membro Participativo

    I want to add a path to the end of the URL of websocket server, but it does not work. For example ws://111.111.11.111:8080/websocket. I want to add URL path /websocket after the port number like this. How do I do it?

    1. First I tested, on the client side, ws://111.111.11.111:8080/websocket.
    2. And secondly, changed URL to ws://111.111.11.111:8080.

    The result was both connected to the server. And show the same output. Why? Can't it be connected only when the /websocket path is specified? What should I do?

    Server side code


    import websockets

    async def web_server(websocket, path):
    while True:
    publish_to_client = json.dumps(sub.status)
    await websocket.send(publish_to_client)
    await asyncio.sleep(0.1)

    if __name__ == "__main__":
    start_server = websockets.serve(web_server, "111.111.11.111", 8080)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

    Client side code -> showing web


    <!DOCTYPE html>
    <html>
    <head>
    <title>WebSocket demo</title>
    </head>
    <body>
    <script>
    var ws = new WebSocket("ws://111.111.11.111:8080/websocket"),
    messages = document.createElement('ul');
    ws.onmessage = function (event) {
    var messages = document.getElementsByTagName('ul')[0],
    message = document.createElement('li'),
    content = document.createTextNode(event.data);
    message.appendChild(content);
    messages.appendChild(message);
    };
    document.body.appendChild(messages);
    </script>
    </body>
    </html>

    Continue reading...

Compartilhe esta Página