2

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>
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Ky P
  • 31
  • 3

2 Answers2

1

The Python code has no mention of the path "/websocket" anywhere inside of it so I wouldn't expect it to do the filtering you desire.

start_server = websockets.serve(web_server, "111.111.11.111", 8080)

The server is bound to an IP address and a port. Any incoming websocket connection will be dispatched to web_server(), no matter the path.

async def web_server(websocket, path):
    ...

This method handles all websockets. It's passed the path and it can use that information however it wishes. The method you wrote doesn't check the path variable so it will handle requests at any path as long as the IP address and port are correct.

If you want only certain paths to be accepted then you'll need to implement that logic yourself. Check path and accept or reject them with whatever logic you desire.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

Just to clarify what has been discussed here, the Server publishes everything with an IP and a port number. The client needs to connect to the correct IP and port to retrieve the data.

If the server decides to send the data for clients with a specific address(as intended in here, e.g ws://192.168.56.1:7890/ws/myApp), then the server needs to set a condition to send the information out for clients that has connected with that address path.

So, in the server side,

....
async def WS_Server(websocket, path):


               if path == '/ws/myApp':
                    
                    await websocket.send(lineJSON)
                    
                
                else:
                    
                    print("Web Socket address path is wrong!")
                    print("\nClient must connect to ws://<yourIP>:<serverPort>/ws/driverapp.")
                    
         


....


async def main():
    async with websockets.serve(WS_Server,"192.168.56.1",PORT):
        await asyncio.Future()  # run forever

asyncio.run(main())
 
M.Emin
  • 63
  • 7