Issue
From the next test code
async def hello():
uri = "ws://localhost:8765"
while True:
async with websockets.connect(uri) as ws:
await ws.send("Test \n")
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(hello())
This code performs the desired behavior of sending a message each second, yet it seems that it could be more efficient by doing the changes shown below:
async def hello():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as ws:
while True:
await ws.send("Test \n")
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(hello())
But, in this second approach, the context manager exits and outputs the next exception:
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason
Why is the context manager closing the connection if the body is properly indented within the context manager?
Solution
You are probably following websockets
library example.
As written in the example:
On the server side, websockets executes the handler coroutine hello once for each WebSocket connection. It closes the connection when the handler coroutine returns.
Below is Websockets server from the example:
import asyncio
import websockets
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
start_server = websockets.serve(hello, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
And Websockets client modified to use while True
loop:
import asyncio
import websockets
async def hello():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
name = input("What's your name? ")
while True:
print(websocket.closed)
await websocket.send("Test")
await asyncio.sleep(1)
print(f"> {name}")
greeting = await websocket.recv()
print(f"< {greeting}")
asyncio.get_event_loop().run_until_complete(hello())
Running the server and then the client provides the following output:
In server:
< Test
> Hello Test!
In client:
What's your name? hi
False
True
...
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason
In the first case you presented, the code creates websocket connection every loop iteration. Whereas in the second, the code reuses the connection which is closed by the server after handling as the documentation states. You can see that the websocket
connection is closed by inspecting websocket.closed
field.
Answered By - rok
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.