Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python瓶子/gevent Websocket检测Websocket何时断开连接_Python_Sockets_Websocket_Bottle_Gevent - Fatal编程技术网

使用Python瓶子/gevent Websocket检测Websocket何时断开连接

使用Python瓶子/gevent Websocket检测Websocket何时断开连接,python,sockets,websocket,bottle,gevent,Python,Sockets,Websocket,Bottle,Gevent,我正在使用gevent-websocket模块和battlePython框架 当客户端关闭浏览器时,此代码 $(window).on('beforeunload', function() { ws.close(); }); 有助于正确关闭websocket连接 但是如果客户端的网络连接中断,则无法向服务器发送“关闭”信息 然后,通常,甚至1分钟后,服务器仍然相信客户端已连接,并且服务器上的websocket仍然打开 问题:如何正确检测由于客户端与网络断开连接而导致websocket关闭? Py

我正在使用
gevent-websocket
模块和
battle
Python框架

当客户端关闭浏览器时,此代码

$(window).on('beforeunload', function() { ws.close(); });
有助于正确关闭websocket连接

但是如果客户端的网络连接中断,则无法向服务器发送“关闭”信息

然后,通常,甚至1分钟后,服务器仍然相信客户端已连接,并且服务器上的websocket仍然打开

问题:如何正确检测由于客户端与网络断开连接而导致websocket关闭?

Python/瓶子/gevent websocket中是否有websocket KeepAlive功能?


来自的一个答案建议每x秒使用心跳/ping数据包告诉服务器“我还活着”。另一个答案建议使用
setKeepAlive(true)。
功能。此功能是否在
gevent websocket
中可用


示例服务器代码:


首先,需要向receive()方法添加超时


然后循环将不会阻塞,如果您发送一个空数据包,而客户机没有响应,那么WebsocketError将被抛出,您可以关闭套接字

首先需要向receive()方法添加超时


然后循环将不会阻塞,如果您发送一个空数据包,而客户机没有响应,那么WebsocketError将被抛出,您可以关闭套接字

我猜这不是你想听的?我猜这不是你想听的?
from bottle import get, template, run
from bottle.ext.websocket import GeventWebSocketServer
from bottle.ext.websocket import websocket

users = set()

@get('/')
def index():
    return template('index')

@get('/websocket', apply=[websocket])
def chat(ws):
    users.add(ws)
    while True:
        msg = ws.receive()
        if msg is not None:
            for u in users:
                u.send(msg)
        else:
            break
    users.remove(ws)

run(host='127.0.0.1', port=8080, server=GeventWebSocketServer)
with gevent.Timeout(1.0, False):
    msg = ws.receive()