pip install flask-socketio
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_key'
socketio = SocketIO()
socketio.init_app(app, cors_allowed_origins='*') # Solving cross domain problems
name_space = '/dcenter'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/push')
def push_once():
event_name = 'dcenter'
broadcasted_data = {
'data': "test message!"}
# Event message sent by the server to the front end
socketio.emit(event_name, broadcasted_data, broadcast=False, namespace=name_space)
return 'done!'
@socketio.on('connect', namespace=name_space)
def connected_msg():
print('client connected.')
@socketio.on('disconnect', namespace=name_space)
def disconnect_msg():
print('client disconnected.')
# The back end receives event messages
@socketio.on('my_event', namespace=name_space)
def mtest_message(message):
# Different events
print(message)
emit('my_response',
{
'data': message['data'], 'count': 1})
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000, debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SocketIO Demo</title>
<script type="text/javascript" src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.socket.io/4.4.1/socket.io.js"></script>
</head>
<body>
<h2>Demo of SocketIO</h2>
<div id="t"></div>
<script> $(document).ready(function () {
namespace = '/dcenter'; var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace); // The front end sends messages socket.emit('my_event',{
'data':'hello world'}); // The front end receives messages socket.on('dcenter', function (res) {
var t = res.data; if (t) {
$("#t").append(t).append('<br/>'); } }); socket.on('my_response', function (res) {
var t = res.data; if (t) {
$("#t").append(t).append('<br/><br/>'); } }) }); </script>
</body>
</html>
What needs to be noted here is , Now I'm using flask-socketio
The version is 5.2, Corresponding front end is required socket.io
The version is 4.x
, Otherwise, an error will be reported .
The following steps show how t
ForewordI pass by the manor, b