aio-libs / aio-libs/aiohttp

ClientWebSocketResponse: Add way to get close message when using msg iterator

Đang mở
#7,682 1 bình luận 0 reaction 0 người được giao Xem trên GitHub
enhancement
Ngôn ngữ chính
Python
Star
16.5k
Fork
2.4k
Merge trung bình
17 giờ 22 phút
Pull request đã merge (30 ngày)
212

Mô tả

### Is your feature request related to a problem?

The websocket server I'm connecting to will send a close message. I want to get this message.

There doesn't seem to a way to do this when using the async message iterator on ClientWebSocketResponse:

e.g.

async with session.ws_connect('http://example.org/ws') as ws:
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
await ws.send_str(msg.data + '/answer')
elif msg.type == aiohttp.WSMsgType.ERROR:
break
# No way to get close message here

### Describe the solution you'd like

There should be a `ClientWebSocketResponse.close_message` property that is set when the server has sent a close message

### Describe alternatives you've considered

As a workaround, I'm using the `ClientWebSocketResponse.receive()` method instead of async message iterator. Then I'm able to handle the close message my self. E.g.:

close_msg = None
async with session.ws_connect('http://example.org/ws') as ws:
while True:
msg = await ws.receive()
if msg.type == aiohttp.WSMsgType.TEXT:
await ws.send_str(msg.data + '/answer')
elif msg.type == aiohttp.WSMsgType.ERROR:
break
elif msg.type == WSMsgType.CLOSE:
close_msg = msg.extra
break
logger.info(f"Closed: {ws.close_code} {close_msg}")

### Related component

Client

### Additional context

_No response_

### Code of Conduct

- [X] I agree to follow the aio-libs Code of Conduct

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.