title: Gevent-Websocket Detecting closed connection
body: <p>I'm using gevent-websocket with bottle.py to serve log-files. 
  How can I detect that the websocket connection is closed from the client-side?</p>
  
  <p>At the moment I'm just writing until I get a broken pipe error:</p>
  
  <pre><code>return sock.send(data, flags)
  error: [Errno 32] Broken pipe
  </code></pre>
  
  <p>But I would like to properly detect on the server if the client closed the websocket connection.</p>
  
  <p>My code looks like:</p>
  
  <pre><code>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/&lt;filename&gt;')
  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()
  </code></pre>
  
  <p>and the corresponding client javascript code:</p>
  
  <pre><code>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 + "&lt;br&gt;" );
        };
  
        window.onbeforeunload = function() {
          ws.onclose = function () {console.log('unlodad')};
          ws.close()
        };
  });
  </code></pre>
  
  <p>Any other improvements to my code or solution are welcome.</p>