Gevent-Websocket 检测关闭连接

6 投票
1 回答
5702 浏览
提问于 2025-04-17 16:11

我正在用gevent-websocket和bottle.py来提供日志文件服务。请问我怎么才能知道客户端关闭了websocket连接呢?

现在我只是一直写数据,直到出现一个叫“broken pipe”的错误:

return sock.send(data, flags)
error: [Errno 32] Broken pipe

但我想在服务器端正确地检测到客户端关闭了websocket连接。

我的代码是这样的:

from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
import gevent.monkey
gevent.monkey.patch_all()
from bottle import route, Bottle, view, request, static_file
import json
import os
import time

app = Bottle()

# Other code

@app.route('/websocket/<filename>')
def ws_logfile(filename):
    if request.environ.get('wsgi.websocket'):
        ws = request.environ['wsgi.websocket']
        try:
            filename = os.path.join(os.getcwd(), "logfiles", filename)
            logfile = file(filename)
            lines = logfile.readlines()
            for line in lines:
                ws.send(json.dumps({'output': line}))

            while True:
                line = logfile.readline()
                if line:
                    # Here detect if connection is closed 
                    # form client then break out of the while loop
                    ws.send(json.dumps({'output': line}))
                else:
                    time.sleep(1)
             ws.close()   

         except geventwebsocket.WebSocketError, ex:
             print "connection closed"
             print '%s: %s' % (ex.__class__.__name__, ex)

if __name__ == '__main__':
     http_server = WSGIServer(('127.0.0.1', 8000), app, handler_class=WebSocketHandler)
     http_server.serve_forever()

还有对应的客户端JavaScript代码:

jQuery(document).ready(function(){
      ws = $.gracefulWebSocket("ws://" + document.location.host + "/websocket" + document.location.pathname);

      ws.onmessage = function (msg) {
        var message = JSON.parse(msg.data);
        $("#log").append(message.output + "<br>" );
      };

      window.onbeforeunload = function() {
        ws.onclose = function () {console.log('unlodad')};
        ws.close()
      };
});

如果你有其他对我的代码的改进建议或者解决方案,也欢迎分享。

1 个回答

7

在通过套接字发送数据之前,先检查一下 if ws.socket is not None: 这个条件。

撰写回答