gpt4 book ai didi

python - 调用 WebSocket.close 时现有等待会发生什么

转载 作者:行者123 更新时间:2023-12-03 17:00:25 25 4
gpt4 key购买 nike

如果我打开 Starlette/FastAPI WebSocket,如果我从协程外部关闭 WebSocket,当前等待从客户端接收数据的协程会发生什么?是否调用 receive引发异常还是协程永远留在内存中,因为它永远不会收到任何东西?

from fastapi import FastAPI
from fastapi.websockets import WebSocket

app = FastAPI()

open_sockets = {}

@app.websocket('/connection/')
async def connection(websocket: WebSocket):
await websocket.accept()

id = await websocket.receive_json()['id']
open_sockets[id] = websocket

while True:
data = await websocket.receive_json()

@app.post('/kill/{id}/')
async def kill(id=str):
# What does this do to the above `await websocket.receive_json()`?
await open_sockets[id].close()
del open_sockets[id]

最佳答案

它引发了 starlette.websockets.WebSocketDisconnect使用代码 1006

  File ".\websocket_close_test.py", line 27, in connection
data = await websocket.receive_json()
File "C:\Apps\Python38\lib\site-packages\starlette\websockets.py", line 98, in receive_json
self._raise_on_disconnect(message)
File "C:\Apps\Python38\lib\site-packages\starlette\websockets.py", line 80, in _raise_on_disconnect
raise WebSocketDisconnect(message["code"])

我确实注意到 .close() 调用阻塞了一段时间。

这是我用来测试的代码,第二个 ws.send从未收到。

import time

import requests
import websocket

ws = websocket.WebSocket()
ws.connect("ws://localhost:8000/connection/")
print('Sending id 0')
ws.send('{ "id": "0" }')
time.sleep(2)
print('Closing id 0')
requests.post('http://localhost:8000/kill/0/')
print('id 0 is closed')
time.sleep(2)
print('Trying to send data on closed connection')
ws.send('{ "id": "10" }')

关于python - 调用 WebSocket.close 时现有等待会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61688444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com