我使用flask和flask\u socketio获取实时数据,mainpy代码和index.html如下:
from flask import Flask, render_template, jsonify, request
from flask_socketio import SocketIO, emit
app=Flask(__name__)
socketio = SocketIO(
app,
cors_allowed_origins="*")
values=[]
random_decimal=[]
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('connect')
def on_connect():
data = get_some_data()
emit('after connect', {'data':data})
def get_some_data():
value = request.args.get('test')
values.append(value)
random_decimal= str(values)
return random_decimal
if __name__=='__main__':
socketio.run(app, debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SocketIO example</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//sending connect request to the server
var socket = io.connect('http://127.0.0.1:5000');
socket.on('after connect', function(msg){
console.log('after connect', msg);
$('#log').append('<br>'+ $('<div/>').text('Received: ' + msg.data).html());
});
});
</script>
</head>`enter code here`
<body>`enter code here`
<h1>SocketIO Example</h1>
<h2>Receive:</h2>
<div id="log"></div>
</body>
</html>
虽然客户端和服务器连接在一起,但我没有得到任何价值。我的代码有什么问题。我认为索引中的客户机代码有问题。
暂无答案!
目前还没有任何答案,快来回答吧!