参考:https://www.hi-roy.com/2015/12/29/flask-socketio%E4%B8%AD%E6%96%87%E6%96%87%E6%A1%A3/
https://www.cnblogs.com/luozx207/p/9714487.html
Socket.IO
SocketIO.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta charset="utf-8" /> 5 <title></title> 6 <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> 7 <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script> 8 </head> 9 <body> 10 <h1 id="t"></h1> 11 <script type="text/javascript"> 12 $(document).ready(function() { 13 namespace = ‘/test_conn‘; 14 //var socket = io.connect(location.protocol + ‘//‘ + document.domain + ‘:‘ + location.port + namespace, {transports: [‘websocket‘]}); 15 var socket = io.connect(‘http://‘ + document.domain + ‘:‘ + location.port + namespace); 16 17 socket.on(‘server_response‘, function(res) { 18 console.log(res.data); 19 $(‘#t‘).text(res.data); 20 }); 21 }); 22 </script> 23 </body> 24 </html>
videws.py
1 from datetime import datetime 2 from flask import render_template 3 from FlaskWebProject1 import app 4 5 @app.route(‘/‘) 6 @app.route(‘/home‘) 7 def home(): 8 """Renders the home page.""" 9 return render_template( 10 ‘index.html‘, 11 title=‘Home Page‘, 12 year=datetime.now().year, 13 ) 14 15 @app.route(‘/contact‘) 16 def contact(): 17 """Renders the contact page.""" 18 return render_template( 19 ‘contact.html‘, 20 title=‘Contact‘, 21 year=datetime.now().year, 22 message=‘Your contact page.‘ 23 ) 24 25 @app.route(‘/about‘) 26 def about(): 27 """Renders the about page.""" 28 return render_template( 29 ‘about.html‘, 30 title=‘About‘, 31 year=datetime.now().year, 32 message=‘Your application description page.‘ 33 ) 34 35 @app.route(‘/SocketIO‘) 36 def SocketIO(): 37 print("In SocketIO ") 38 return render_template(‘SocketIO.html‘)
runserver.py
1 from os import environ 2 from FlaskWebProject1 import app 3 from flask_socketio import SocketIO,emit 4 5 from threading import Lock 6 import random 7 async_mode = None 8 #app = Flask(__name__) 9 app.config[‘SECRET_KEY‘] = ‘secret!‘ 10 socketio = SocketIO(app) 11 thread = None 12 thread_lock = Lock() 13 14 @socketio.on(‘connect‘, namespace=‘/test_conn‘) 15 def test_connect(): 16 print("In test_connect ") 17 global thread 18 with thread_lock: 19 if thread is None: 20 thread = socketio.start_background_task(target=background_thread) 21 22 def background_thread(): 23 print("In background_thread ") 24 while True: 25 socketio.sleep(1) 26 t = random.randint(1, 100) 27 socketio.emit(‘server_response‘, 28 {‘data‘: t},namespace=‘/test_conn‘) 29 30 31 if __name__ == ‘__main__‘: 32 HOST = environ.get(‘SERVER_HOST‘, ‘0.0.0.0‘) 33 try: 34 PORT = int(environ.get(‘SERVER_PORT‘, ‘5555‘)) 35 except ValueError: 36 PORT = 5555 37 #app.run(HOST, PORT) 38 socketio.run(app,HOST, PORT,debug=True)
原文:https://www.cnblogs.com/kingboy100/p/12747118.html