diff options
| author | Ryan Williams <breath@alum.mit.edu> | 2010-08-13 11:45:56 -0700 |
|---|---|---|
| committer | Ryan Williams <breath@alum.mit.edu> | 2010-08-13 11:45:56 -0700 |
| commit | a462dd4dbcf32a212ea17f415be78680a010449f (patch) | |
| tree | 42ef5c211c368a85edddb6b0e51d43d2c084ddf1 /examples | |
| parent | 74d1ceaa06a33675f8f9444d0de5482dd9459495 (diff) | |
| download | eventlet-a462dd4dbcf32a212ea17f415be78680a010449f.tar.gz | |
Added websocket multi-user chat example for Luca Zago's question.
Diffstat (limited to 'examples')
| -rw-r--r-- | examples/websocket_chat.html | 34 | ||||
| -rw-r--r-- | examples/websocket_chat.py | 34 |
2 files changed, 68 insertions, 0 deletions
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 @@ +<!DOCTYPE html> +<html> +<head> +<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> +<script> +window.onload = function() { + var data = {}; + var s = new WebSocket("ws://127.0.0.1:7000/chat"); + s.onopen = function() { + s.send('New participant joined'); + }; + s.onmessage = function(e) { + $("#chat").append("<div>" + e.data + "</div>"); + }; + $('#chatform').submit(function (evt) { + var line = $('#chatform [type=text]').val() + $('#chatform [type=text]').val('') + s.send(line); + return false; + }); +}; +</script> +</head> +<body> +<h3>Chat!</h3> +<p>(Only tested in Chrome)</p> +<div id="chat" style="width: 60em; height: 20em; overflow:auto; border: 1px solid black"> +</div> +<form id="chatform"> +<input type="text" /> +<input type="submit" /> +</form> +</body> +</html> 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) |
