Created
January 9, 2018 08:14
-
-
Save dj-shin/bbf055f1e2c29adf23357b8368d8aeaf to your computer and use it in GitHub Desktop.
Flask 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
$(document).ready(function() { | |
connectionString = 'http://' + location.host | |
console.log('Connecting web socket: '+connectionString) | |
ws = io.connect(connectionString); | |
console.log('Registering function clicks') | |
$( "p" ).on( "click", function() { | |
ws.send('request', {who: $(this).attr('id'), data: $(this).val()}); | |
}); | |
}); |
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 flask import Flask, render_template | |
from flask_socketio import SocketIO, emit | |
import logging | |
logging.basicConfig(level=logging.INFO) | |
logger = logging.getLogger(__name__) | |
app = Flask(__name__) | |
socketio = SocketIO(app) | |
@app.route('/') | |
def hello_world(): | |
logger.info('Serving root') | |
return render_template('index.html') | |
@socketio.on('my event') | |
def respondToRequest(message): | |
logger.info('responding to request') | |
emit('my response',{'data':'some response'}) | |
if __name__ == '__main__': | |
logger.info('Running socket IO') | |
socketio.run(app, host='0.0.0.0', port=10001) |
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 Websockets Demo</title> | |
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> | |
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script> | |
<script type="text/javascript" src="static/js/application.js"></script> | |
</head> | |
<body> | |
<p>Click me</p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment