| 1 |
import os |
| 2 |
|
| 3 |
import eventlet |
| 4 |
from eventlet import wsgi |
| 5 |
from eventlet import websocket |
| 6 |
|
| 7 |
PORT = 7000 |
| 8 |
|
| 9 |
participants = set() |
| 10 |
|
| 11 |
|
| 12 |
@websocket.WebSocketWSGI |
| 13 |
def handle(ws): |
| 14 |
participants.add(ws) |
| 15 |
try: |
| 16 |
while True: |
| 17 |
m = ws.wait() |
| 18 |
if m is None: |
| 19 |
break |
| 20 |
for p in participants: |
| 21 |
p.send(m) |
| 22 |
finally: |
| 23 |
participants.remove(ws) |
| 24 |
|
| 25 |
|
| 26 |
def dispatch(environ, start_response): |
| 27 |
"""Resolves to the web page or the websocket depending on the path.""" |
| 28 |
if environ['PATH_INFO'] == '/chat': |
| 29 |
return handle(environ, start_response) |
| 30 |
else: |
| 31 |
start_response('200 OK', [('content-type', 'text/html')]) |
| 32 |
html_path = os.path.join(os.path.dirname(__file__), 'websocket_chat.html') |
| 33 |
return [open(html_path).read() % {'port': PORT}] |
| 34 |
|
| 35 |
if __name__ == "__main__": |
| 36 |
# run an example app from the command line |
| 37 |
listener = eventlet.listen(('127.0.0.1', PORT)) |
| 38 |
print("\nVisit http://localhost:7000/ in your websocket-capable browser.\n") |
| 39 |
wsgi.server(listener, dispatch) |