From a462dd4dbcf32a212ea17f415be78680a010449f Mon Sep 17 00:00:00 2001 From: Ryan Williams Date: Fri, 13 Aug 2010 11:45:56 -0700 Subject: [PATCH] Added websocket multi-user chat example for Luca Zago's question. --- doc/examples.rst | 10 ++++++++++ examples/websocket_chat.html | 34 ++++++++++++++++++++++++++++++++++ examples/websocket_chat.py | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 examples/websocket_chat.html create mode 100644 examples/websocket_chat.py diff --git a/doc/examples.rst b/doc/examples.rst index c16bf26..dd6574e 100644 --- a/doc/examples.rst +++ b/doc/examples.rst @@ -94,3 +94,13 @@ This exercises some of the features of the websocket server implementation. .. literalinclude:: ../examples/websocket.py + +.. _websocket_chat_example: + +Websocket Multi-User Chat Example +-------------------------- +``examples/websocket_chat.py`` + +This is a mashup of the websocket example and the multi-user chat example, showing how you can do the same sorts of things with websockets that you can do with regular sockets. + +.. literalinclude:: ../examples/websocket_chat.py diff --git a/examples/websocket_chat.html b/examples/websocket_chat.html new file mode 100644 index 0000000..3eb7efc --- /dev/null +++ b/examples/websocket_chat.html @@ -0,0 +1,34 @@ + + + + + + + +

Chat!

+

(Only tested in Chrome)

+
+
+
+ + +
+ + diff --git a/examples/websocket_chat.py b/examples/websocket_chat.py new file mode 100644 index 0000000..7f7e3ea --- /dev/null +++ b/examples/websocket_chat.py @@ -0,0 +1,34 @@ +import eventlet +from eventlet import wsgi +from eventlet import websocket + +participants = set() + +@websocket.WebSocketWSGI +def handle(ws): + participants.add(ws) + try: + while True: + m = ws.wait() + if m is None: + break + for p in participants: + p.send(m) + finally: + participants.remove(ws) + +def dispatch(environ, start_response): + """Resolves to the web page or the websocket depending on the path.""" + if environ['PATH_INFO'] == '/chat': + return handle(environ, start_response) + else: + start_response('200 OK', [('content-type', 'text/html')]) + return [open(os.path.join( + os.path.dirname(__file__), + 'websocket_chat.html')).read()] + +if __name__ == "__main__": + # run an example app from the command line + listener = eventlet.listen(('127.0.0.1', 7000)) + print "\nVisit http://localhost:7000/ in your websocket-capable browser.\n" + wsgi.server(listener, dispatch)