程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python uses flask socketio

編輯:Python

install flask-socketio

pip install flask-socketio

Server side

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)

front end

<!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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved