Created
September 1, 2011 07:17
-
-
Save lrvick/1185629 to your computer and use it in GitHub Desktop.
Simple Websocket echo client/server with Flask and gevent / gevent-websocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from geventwebsocket.handler import WebSocketHandler | |
from gevent.pywsgi import WSGIServer | |
from flask import Flask, request, render_template | |
app = Flask(__name__) | |
@app.route('/') | |
def index(): | |
return render_template('index.html') | |
@app.route('/api') | |
def api(): | |
if request.environ.get('wsgi.websocket'): | |
ws = request.environ['wsgi.websocket'] | |
while True: | |
message = ws.wait() | |
ws.send(message) | |
return | |
if __name__ == '__main__': | |
http_server = WSGIServer(('',5000), app, handler_class=WebSocketHandler) | |
http_server.serve_forever() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<html> | |
<head> | |
<title>Flask/Gevent WebSocket Test</title> | |
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> | |
<script type="text/javascript" charset="utf-8"> | |
$(document).ready(function(){ | |
$('form').submit(function(event){ | |
ws.send($('#data').val()) | |
return false; | |
}); | |
if ("WebSocket" in window) { | |
ws = new WebSocket("ws://" + document.domain + ":5000/api"); | |
ws.onmessage = function (msg) { | |
$("#log").append("<p>"+msg.data+"</p>") | |
}; | |
} else { | |
alert("WebSocket not supported"); | |
} | |
}); | |
</script> | |
</head> | |
<body> | |
<h1>Send:</h1> | |
<form method='POST' action='#'> | |
<textarea name='data' id="data"></textarea> | |
<div><input type='submit'></div> | |
</form> | |
<h1>Receive:</h1> | |
<div id="log"></div> | |
</body> | |
</html> |
Something that tripped me up:
Make sure to put the "index.html" file inside a folder called "templates". If you put it next to flask_geventwebsocket_example.py flask won't find it.
semi colon is missing in index.html : line 9
Is there a way to achieve the same without the while True?
get messenger of cliente use ws.receive()
how could I set cross_origin="*" for the websocket?
@Zaniyer need public address
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The wait() method was renamed to receive(). http://www.gelens.org/code/gevent-websocket/