2013-02-17 299 views
6

我使用gevent-websocket和bottle.py来提供日志文件。 如何检测WebSocket连接是否从客户端关闭?Gevent-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() 
     }; 
}); 

任何其他改善我的代码或解决方案是受欢迎的。

回答

7

尝试测试if ws.socket is not None:,然后再在套接字上发送数据。

+3

更好的要求原谅而不是允许。还有一个竞赛条件。 – warvariuc 2015-01-09 07:39:01