I've followed this simple tutorial on sync two clients on flask, I'm running it locally but opening two tabs of "localhost" do not make my sliders sync.
https://www.matthieuamiguet.ch/blog/synchronize-clients-flask-application-websockets
I am working on pycharm, on a venv.
I get "GET / HTTP/1.1" 200 -
I tried both debug mode on and off.
Code below:
app.py
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")
values = {
'slider1': 25,
'slider2': 0,
}
@app.route('/')
def index():
return render_template('index.html', **values)
@socketio.on('value changed')
def value_changed(message):
values[message['who']] = message['data']
emit('update value', message, broadcast=True)
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0')
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Synchronized Sliders</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var socket = io.connect();
socket.on('connect', function() {
socket.emit('connect', {data: 'I\'m connected!'});
});
$('input.sync').on('input', function(event) {
socket.emit('value changed', {who: $(this).attr('id'), data: $(this).val()});
return false;
});
socket.on('update value', function(msg) {
$('input#'+msg.who).val(msg.data)
});
});
</script>
</head>
<body>
<h1>Synchronized Sliders!</h1>
<input id="slider1" class="sync" type="range" min="0" max="50" value="{{slider1}}" /> <br>
<input id="slider2" class="sync" type="range" min="0" max="50" value="{{slider2}}" />
<input id="txt1" class="sync" type="text" />
</body>
</html>
Found the solution by replacing on the index.html
var socket = io.connect();
by
var socket = io.connect(my ip);
You can check it by typing ipconfig on a cmd window and setting the number from the IPv4 Address.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.