5

如果我打开 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]
4

1 回答 1

2

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" }')
于 2020-05-19T03:26:25.073 回答