websocket.py 1.2 KB

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