Websockets server with anvil

Hi all,

Is it possible to setup a websockets server with anvil?

Code below works great when running it on my local computer, but it seems that this code cannot be run in a server-side script in anvil? is that correct?

import asyncio
import websockets

async def handle_websocket(websocket, path):
    # This function will be called whenever a new WebSocket connection is established
    print(f"Client connected to {path}")

    try:
        while True:
            # Wait for data from the client
            message = await websocket.recv()
            print(f"Received message: {message}")

            # Send a response back to the client
            response = f"Received: {message}"
            await websocket.send(response)

    except websockets.exceptions.ConnectionClosed:
        # Handle the case where the connection is closed
        print(f"Client disconnected from {path}")

# Set up the WebSocket server
start_server = websockets.serve(handle_websocket, "localhost", 8765)

# Start the event loop to run the server
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

I know that i normally can run a uplink (client) but it is not possible in this case since the websockets client code is/will be run from a C# application.

Any help is appreciated!

In order for your function to work, it should start and keep running forever.

The Anvil server will kill any function that runs longer than 30 seconds, unless it’s in a background task. And even if it’s in a background task, it could be killed at will.

You may be able to use sockets for short lived tasks, but it’s unlikely to work with long running ones.

With anvil-app-server:

runtime_options: {‘server_persist’ : True}

enables persistent server modules. I wonder if your code would run as needed with that configuration.

Even with persistent server, processes can be killed. It’s unlikely, most of the time the same process keeps responding, but it is not guaranteed.

Thanks, I will try that! So I can pick any port of choice for the websockets server?

I would probably run a separate websockets server and use the uplink from there to access anvil data or server-side functions.

1 Like

Thanks! Yeah I am considering that :slight_smile: