Search code examples
pythonwebsocketserverclient

How to connect to websocket server across devices?


So I'm trying to get a websocket working with the websockets Python module. The websockets docs have some simple server and client examples, and they work fine when running on the same device, but when I try to use it across devices, it won't connect. I'm new to websockets, so any help would be appreciated.

Here's the echo server example from the websockets docs:

import asyncio
from websockets.server import serve

async def echo(websocket):
    async for message in websocket:
        await websocket.send(message)

async def main():
    async with serve(echo, "localhost", 8765):
        await asyncio.Future()  # run forever

asyncio.run(main())

and here's the client example:

import asyncio
from websockets.sync.client import connect

def hello():
    with connect("ws://localhost:8765") as websocket:
        websocket.send("Hello world!")
        message = websocket.recv()
        print(f"Received: {message}")

hello()

I looked through the websockets docs. A lot of it went over my head, but a section was talking about deploying the server to some hosting service. I want to know if it's possible just to run my computer as the server, and have other people connect over the internet without using this kind of service.


Solution

  • Never mind I figured it out. In case anyone needs to know, the server should be:

    import asyncio
    from websockets.server import serve
    
    async def echo(websocket):
        async for message in websocket:
            await websocket.send(message)
            print('recieved request')
    
    async def main():
        async with serve(echo, "", 3324):
            await asyncio.Future()  # run forever
    
    asyncio.run(main())
    

    and the client should be:

    import asyncio
    from websockets.sync.client import connect
    
    def hello():
        with connect("ws://xxx.xxx.x.xx:3324") as websocket:
        websocket.send("Hello world!")
        message = websocket.recv()
        print(f"Received: {message}")
    
    hello()
    

    where the x's are the IP address of the host.