Skip to content

Instantly share code, notes, and snippets.

@theriley106
Created February 16, 2019 00:17
Show Gist options
  • Save theriley106/d515b5a1384ee2988d12b05e83f0149b to your computer and use it in GitHub Desktop.
Save theriley106/d515b5a1384ee2988d12b05e83f0149b to your computer and use it in GitHub Desktop.
Web Socket Example
# Copy of http://stackoverflow.com/a/20104705
from flask import Flask, render_template
from flask_sockets import Sockets
import datetime
import time
app = Flask(__name__)
sockets = Sockets(app)
@sockets.route('/echo')
def echo_socket(ws):
while True:
#message = ws.receive()
ws.send(str(datetime.datetime.now()))
time.sleep(.1)
@app.route('/')
def hello():
return 'Hello World!'
@app.route('/echo_test', methods=['GET'])
def echo_test():
return render_template('example.html')
if __name__ == '__main__':
app.run()
# Start with gunicorn -k flask_sockets.worker app:app
<!DOCTYPE html>
<html>
<head>
</head>
<p id="test">Testing</p>
<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) {
document.getElementById("test").innerHTML = evt.data;
};
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment