Last active
December 21, 2023 23:36
-
-
Save punchagan/53600958c1799c2dcf26 to your computer and use it in GitHub Desktop.
A simple Flask sockets example
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
# Copy of http://stackoverflow.com/a/20104705 | |
from flask import Flask, render_template | |
from flask_sockets import Sockets | |
app = Flask(__name__) | |
app.debug = True | |
sockets = Sockets(app) | |
@sockets.route('/echo') | |
def echo_socket(ws): | |
while True: | |
message = ws.receive() | |
ws.send(message[::-1]) | |
@app.route('/') | |
def hello(): | |
return 'Hello World!' | |
@app.route('/echo_test', methods=['GET']) | |
def echo_test(): | |
return render_template('echo_test.html') | |
if __name__ == '__main__': | |
app.run() |
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> | |
<script type="text/javascript"> | |
var ws = new WebSocket("ws://localhost:8000/echo"); | |
ws.onopen = function() { | |
ws.send("socket open"); | |
}; | |
ws.onclose = function(evt) { | |
alert("socket closed"); | |
}; | |
ws.onmessage = function(evt) { | |
alert(evt.data); | |
}; | |
</script> | |
</head> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The flask_sockets project is now archived and unsupported. We @AdaSupport had issues running it with gunicorn. This snippet solved our problem: