FastAPI Websocket not closing or raising exception after closing the associated Flutter Websocket

Possible Working Solution

After some time digging through StackOverflow and Reddit, i’ve tried the following code within my while True loop:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>try:
await asyncio.wait_for( websocket.receive_text(), timeout=0.1)
except asyncio.TimeoutError:
pass
</code>
<code>try: await asyncio.wait_for( websocket.receive_text(), timeout=0.1) except asyncio.TimeoutError: pass </code>
try:
    await asyncio.wait_for( websocket.receive_text(), timeout=0.1)
except asyncio.TimeoutError:
    pass

It seems to trigger a WebSocketDisconnect exception when the websocket is already closed. For anyone having a similar problem, try it out! I’m going to experiment a bit more with this, and if it does work, i’ll close this issue.

Overview

I’m integrating an endpoint from FastAPI with Flutter in which I establish a Websocket connection. Afterwards, the Flutter frontend closes the Websocket connection via a click on a button.
What’s supposed to happen is the Websocket connection from the FastAPI side to close as well, but the Websocket doesn’t close and no WebSocketDisconnectException is raised, although the Flutter websocket is signalled as closed.
Also, the websocket’s client state remains as CONNECTED even though I closed it.

Flutter Websocket Code

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class RealtimeDataService {
WebSocketChannel? channel;
void start(StreamController<Map> controller, String cameraID) async {
channel = WebSocketChannel.connect(
Uri.parse('ws://localhost:8001/camera/$cameraID'),
);
channel!.stream.listen((event) async {
Map data = bson.BsonCodec.deserialize(bson.BsonBinary.from(event));
controller.add(data);
});
}
void stop() {
if (channel == null) return;
channel!.sink.close();
channel = null;
}
}
</code>
<code>class RealtimeDataService { WebSocketChannel? channel; void start(StreamController<Map> controller, String cameraID) async { channel = WebSocketChannel.connect( Uri.parse('ws://localhost:8001/camera/$cameraID'), ); channel!.stream.listen((event) async { Map data = bson.BsonCodec.deserialize(bson.BsonBinary.from(event)); controller.add(data); }); } void stop() { if (channel == null) return; channel!.sink.close(); channel = null; } } </code>
class RealtimeDataService {
  WebSocketChannel? channel;
  void start(StreamController<Map> controller, String cameraID) async {
    channel = WebSocketChannel.connect(
      Uri.parse('ws://localhost:8001/camera/$cameraID'),
    );
    channel!.stream.listen((event) async {
      Map data = bson.BsonCodec.deserialize(bson.BsonBinary.from(event));
      controller.add(data);
    });
  }

  void stop() {
    if (channel == null) return;
    channel!.sink.close();
    channel = null;
  }
}

FastAPI Websocket Code

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@app.websocket("/camera/{camera_id}")
async def read_camera(websocket: WebSocket, camera_id: int):
await websocket.accept()
try:
while True:
# print(websocket.client_state.name)
print('Running') # Suggested solution from Edit 1
await asyncio.sleep(0.1) # Suggested solution from Edit 1
except WebSocketDisconnect:
print('Client disconnected')
raise HTTPException(status_code=200, detail="Client disconnected")
except:
print('Error capturing camera')
await websocket.close()
raise HTTPException(status_code=200, detail="Camera is not available")
</code>
<code>@app.websocket("/camera/{camera_id}") async def read_camera(websocket: WebSocket, camera_id: int): await websocket.accept() try: while True: # print(websocket.client_state.name) print('Running') # Suggested solution from Edit 1 await asyncio.sleep(0.1) # Suggested solution from Edit 1 except WebSocketDisconnect: print('Client disconnected') raise HTTPException(status_code=200, detail="Client disconnected") except: print('Error capturing camera') await websocket.close() raise HTTPException(status_code=200, detail="Camera is not available") </code>
@app.websocket("/camera/{camera_id}")
async def read_camera(websocket: WebSocket, camera_id: int):
    await websocket.accept()

    try:
        while True:
            # print(websocket.client_state.name)
            print('Running') # Suggested solution from Edit 1
            await asyncio.sleep(0.1) # Suggested solution from Edit 1
    except WebSocketDisconnect:
        print('Client disconnected')
        raise HTTPException(status_code=200, detail="Client disconnected")
    except:
        print('Error capturing camera')
        await websocket.close()
        raise HTTPException(status_code=200, detail="Camera is not available")

I’ve tried receiving messages in the FastAPI websocket, and trying to catch the exception raised when trying to send a message through a websocket that is closed, but it doesn’t seem to change the outcome.
Not only does the websocket not close, I can’t close the FastAPI server with ‘CTRL+C’.

What I need is, after the Flutter websocket is closed, the FastAPI one be closed as well, so I can later reconnect if needed, or simply do other actions.

Edit 1

Tried adding a await asyncio.sleep(0.1) (and a print statement to know that it is running) to the while True loop, but the problem persists. I’ll add below two screenshots showcasing the behaviour at the moment, with this solution.

The intended outcome is to, after closing the websocket from the Flutter side, as ilustrated by the first screenshot, the process to stop running as well.

Output before and after closing the socket from the Flutter side.

Output after using CTRL+C two times in a row.

4

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật