websocket.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import eventlet
  2. from eventlet import wsgi
  3. from eventlet import websocket
  4. # demo app
  5. import os
  6. import random
  7. @websocket.WebSocketWSGI
  8. def handle(ws):
  9. """ This is the websocket handler function. Note that we
  10. can dispatch based on path in here, too."""
  11. if ws.path == '/echo':
  12. while True:
  13. m = ws.wait()
  14. if m is None:
  15. break
  16. ws.send(m)
  17. elif ws.path == '/data':
  18. for i in xrange(10000):
  19. ws.send("0 %s %s\n" % (i, random.random()))
  20. eventlet.sleep(0.1)
  21. def dispatch(environ, start_response):
  22. """ This resolves to the web page or the websocket depending on
  23. the path."""
  24. if environ['PATH_INFO'] == '/data':
  25. return handle(environ, start_response)
  26. else:
  27. start_response('200 OK', [('content-type', 'text/html')])
  28. return [open(os.path.join(
  29. os.path.dirname(__file__),
  30. 'websocket.html')).read()]
  31. if __name__ == "__main__":
  32. # run an example app from the command line
  33. listener = eventlet.listen(('127.0.0.1', 7000))
  34. print "\nVisit http://localhost:7000/ in your websocket-capable browser.\n"
  35. wsgi.server(listener, dispatch)