本文介绍了Python Asyncio Websocket 未检测到 wifi 上的断开连接,但在 localhost 上检测到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

async def relayHandler(request):
print('Websocket connection starting')
ws = aiohttp.web.WebSocketResponse(autoclose=True)
await ws.prepare(request)
print('Websocket connection ready')

async for msg in ws:
    print(msg)
    if msg.type == aiohttp.WSMsgType.TEXT:
        print(msg.data)
        if msg.data == 'close':
            await ws.close()
        else:
            await ws.send_str(msg.data + '/answer')
    elif msg.type == aiohttp.WSMsgType.ERROR:
        print('ws connection closed with exception %s' %ws.exception())
print('Websocket connection closed')
return ws

这是我的 websocket 处理程序,它在 asyncio 之上使用 aiohttp.问题是,如果我断开客户端的 wifi 连接,它不会检测到连接丢失.我也尝试使用 Websockets 模块,但发生了同样的事情.但是当客户端在本地主机上时,那么工作完美.造成这种情况的主要原因是什么,是否有人可以解释如何在 asyncio 中正确捕获网络异常.

this is my websocket handler it uses aiohttp on top of asyncio. The problem is if i disconnect the clients wifi connection its not detecting that the connection is lost. i also tried using the Websockets module, but the same thing happend. But when the client is on localhost then working perfectly.Whats the main reason for this, and if anyone could explain how to properly catch network exceptions inside asyncio.

推荐答案

TLDR;通过客户端 ping 您的服务器.

TLDR; ping your server by client.

这就是 TCP 堆栈的工作原理:正常断开连接需要向对等方发送数据包.如果网络中断,则无法进行数据传输.

That's how TCP stack works: graceful disconnection requires sending a packet to peer. If the network is broken not data transfer is available.

Localhost 网络拥有有关断开连接的所有知识,但真实网络缺少有关所有活动部件的信息.

Localhost network has all the knowledge about disconnections but real network misses the info about all moving parts.

检测断开连接的唯一可靠方法是等待来自对等方的消息(可以是ping 消息或常规数据包)并超时.

The only reliable way to detect disconnection is waiting for a message from peer (it can be ping message or regular data packet) with a timeout.

如果超时 - 对等体消失,通信通道的本地端也应该关闭.

If timeout is expired -- the peer is gone, the local end of communication channel should be closed as well.

这就是为什么通过 TCP 进行的任何长期通信都比看起来更复杂的原因——所有生产级系统都在内部使用 ping 和超时.它不仅会影响 websocket,还会影响任何具有自定义协议的信使.

That's why any long-living communication over TCP is a little more complex than it seems -- all production-level systems use pings and timeouts internally. It affects not only websockets but any messengers with custom protocol.

这篇关于Python Asyncio Websocket 未检测到 wifi 上的断开连接,但在 localhost 上检测到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 20:43