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.
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.