Forums

Can I have ws://user-name.pythonanywhere:8765 accessible to play with Websockets?

Good morning, even if it is evening.

<hr />

I am playing "Just for fun" with Python websockets and asyncio sending some coordinates<br /> to be shown into a p5.js canvas as colored dots connected with colored lines.

<hr />

Locally I can run my "server.py" and have ws://localhost:8765 uri and port accessible to get data into Web page.

<hr />

Now, I need to run my "server.py" on PythonAnywhere to send same data to my Web page,<br /> but as I can see, I could not access the uri and port as ws://user-name.pythonanywhere.com:8765.

<hr />

What can I do?

<hr />

Here is my "server.py" code.

import asyncio
from random import randint
from websockets.asyncio.server import serve

async def generate_coordinates():
    # Generate random x and y coordinates within the given ranges
    x = randint(100, 1100)
    y = randint(100, 700)
    return [x, y]


async def echo(websocket):
    try:
        while True:
            message = await generate_coordinates()
            await websocket.send(f"{message}")
            await asyncio.sleep(0.05)
    except Exception as e:
        print(e)

async def main():
    async with serve(echo, "0.0.0.0", 8765) as server:
        try:
            await server.serve_forever()
        except Exception as e:
            print(e)

if __name__ == "__main__":
    asyncio.run(main())

Here is how coordinates are shown in my Web page over Websockets.

My Web page video preview

Web page image preview

You cannot run a web app from a console. See https://help.pythonanywhere.com/pages/ASGICommandLine/ for how to create a web app that can use websockets.

Seems that PythonAnywhere has no support for Python Websockets,<br /> so I can't play with Python Websockets, even if they are so funny!

Found a temporary solution! I am using "ngrok http 8765" and inserting the forwarding link using "wss://xyz-name.ngrok.link" inserted in my web page that I manage with Bottle on PythonAnywhere, so everything stated to breath, at least for some fun! I am so happy! :)

I am learning Python Websockets, so found this solution to have PythonAnywhere with Web on Bottle, <br /> and Websockets configured on "Deploy to Koyeb" - websockets 15.0.1 documentation: https://websockets.readthedocs.io/en/stable/deploy/koyeb.html

Learning Python Websockets and Bottle on PythonAnywhere! A lot of fun!