I'm trying and failing to use python's websocket library to handle multiple clients at once with asyncio. It doesn't work. It feels like the second connection is waiting for the first one to disconnect. Is this even possible? I have been looking for hours and I can't find anything that works for me.
The server code is as follows (note that the hostname and port are the correct values in the implementation of this code):
import asyncio
import websockets
# identifies the port
PORT = "<port goes here>"
# identifies the hostname
HOST = "<hostname goes here"
# sets the trust message that essentially acts as a secondary handshake
TURTLE_MESSAGE = "Shake my hand bro"
# sets the message that will indicate a disconnection
DISCONNECT_MESSAGE = "END-OF-LINE"
turtles = []
# handles a new connection
async def handle_connect(websocket, path):
print(f"CONNECTION RECIEVED @ {path}")
turtleIndex = len(turtles)
turtles.append(f"Turtle {len(turtles)}")
print(turtles[turtleIndex])
connected = True
first_msg = await websocket.recv()
if first_msg != TURTLE_MESSAGE:
print("Connection Refused")
await websocket.send("return print('Connection Refused')")
await websocket.close()
else:
print("Connection Established")
await websocket.send("return print('Connection Established')")
while connected:
msg = await websocket.recv()
if msg == DISCONNECT_MESSAGE:
break
print(msg)
await websocket.send("return turtle.turnRight()")
print("CLOSING SOCKET")
async def main():
async with websockets.serve(handle_connect, HOST, PORT, ssl=None, compression=None):
await asyncio.Future()
print("STARTING SERVER")
asyncio.run(main())
Thanks