Instantly share code, notes, and snippets.

What would you like to do?
Simple Websocket echo client/server with Flask and gevent / gevent-websocket
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from flask import Flask, request, render_template
app = Flask(__name__)
def index():
return render_template('index.html')
def api():
if request.environ.get('wsgi.websocket'):
ws = request.environ['wsgi.websocket']
while True:
message = ws.wait()
if __name__ == '__main__':
http_server = WSGIServer(('',5000), app, handler_class=WebSocketHandler)
<title>Flask/Gevent WebSocket Test</title>
<script type="text/javascript" src=""></script>
<script type="text/javascript" charset="utf-8">
return false;
if ("WebSocket" in window) {
ws = new WebSocket("ws://" + document.domain + ":5000/api");
ws.onmessage = function (msg) {
} else {
alert("WebSocket not supported");
<form method='POST' action='#'>
<textarea name='data' id="data"></textarea>
<div><input type='submit'></div>
<div id="log"></div>

This comment has been minimized.

kilonet commented Mar 13, 2012

The wait() method was renamed to receive().


This comment has been minimized.

stephenbez commented Aug 13, 2013

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 won't find it.


This comment has been minimized.

mmohansmp commented Apr 2, 2016

semi colon is missing in index.html : line 9


This comment has been minimized.

rolurq commented Sep 23, 2016

Is there a way to achieve the same without the while True?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment