【问题标题】:Gevent-Websocket Detecting closed connectionGevent-Websocket 检测关闭的连接
【发布时间】:2013-02-02 05:46:54
【问题描述】:

我正在使用带有 bottle.py 的 gevent-websocket 来提供日志文件。 如何检测到客户端关闭了 websocket 连接?

目前我只是在写,直到出现管道损坏错误:

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()
      };
});

欢迎对我的代码或解决方案进行任何其他改进。

【问题讨论】:

    标签: python websocket bottle gevent


    【解决方案1】:

    在套接字上发送数据之前尝试测试if ws.socket is not None:

    【讨论】:

    • 请求宽恕比请求许可要好。仍然存在竞争条件。
    猜你喜欢
    • 2016-05-15
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 2019-10-22
    • 2012-08-08
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    相关资源
    最近更新 更多