@test29998411 The reason you are getting the ConnectionClosedOK
error is that the WebSocket connection is being closed after the message is sent. This is because the async with
statement in the connect
function creates a context in which the WebSocket connection is open, and when the context is exited (i.e., when the async with
block is exited), the connection is closed.
To keep the connection open, you can modify the connect
function to use a while
loop that waits for messages and sends responses indefinitely. Here's an example:
async def connect(url):
async with websockets.connect(url) as ws:
print('connected')
while True:
message = await ws.recv()
print('Message received: ' + message)
response = 'Response OK'
await ws.send(response)
This modified connect
function will wait for messages indefinitely and send a response for each message it receives.