Python websockets module tutorial script does not run correctly

Question:

I am trying to mess around with the websockets module from python in order to make a simple chat server. I went to their quick start guide (found here: https://websockets.readthedocs.io/en/stable/howto/quickstart.html) and copied and pasted their server.py script and client.py script:

server.py:

import asyncio
import websockets
import logging

async def hello(websocket):
    name = await websocket.recv()
    print(f"<<< {name}")

    greeting = f"Hello {name}!"

    await websocket.send(greeting)
    print(f">>> {greeting}")

async def main():
    async with websockets.serve(hello, "localhost", 8008):
        logging.basicConfig( #Added by me in order to debug
            format="%(message)s",
            level=logging.DEBUG, 
        )
        await asyncio.Future()  # run forever

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

client.py

import asyncio
import websockets

async def hello():
    uri = "ws://localhost:8008"
    async with websockets.connect(uri) as websocket:
        name = input("What's your name? ")

        await websocket.send(name)
        print(f">>> {name}")

        greeting = await websocket.recv()
        print(f"<<< {greeting}")

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

However, when I run the server and then the client I get the following error in the server.py terminal:

Traceback (most recent call last):
  File "/opt/homebrew/lib/python3.9/site-packages/websockets/legacy/server.py", line 293, in handler
    await self.ws_handler(self, path)
TypeError: hello() takes 1 positional argument but 2 were given

I tried adding logging for debugging and using the visual studio debugger to iterate through the script. Still, I could not see how many arguments were given to the hello() function.

Asked By: PBRParker

||

Answers:

I’ve figured out that the second argument it passes in is "/" (a string). This issue is fixed by simply adding another parameter to the hello() function and then just not using it. However I’m not sure why websockets does this, could it be a bug?

Answered By: PBRParker

The server.py code above is written for websockets 10.0 or later. 10.0 removed the second argument to the handler(). Your websockets package is earlier than 10.0 so hello() is called with a second argument. If you cannot upgrade websockets to 10.0 or later, just add a second dummy argument path to hello().

Answered By: Keith Owens
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.