flask与vue实现通过websocket通信
以下是一个使用Flask和Vue.js实现WebSocket通信的简单示例。
Flask部分(app.py
):
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, send, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('message')
def handle_message(message):
send({'data': message['data']}, broadcast=True)
if __name__ == '__main__':
socketio.run(app, debug=True)
Vue.js部分(index.html
):
<!DOCTYPE html>
<html>
<head>
<title>Flask + Vue.js WebSocket Example</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.0/socket.io.min.js"></script>
</head>
<body>
<div id="app">
<input v-model="message" placeholder="Type your message here">
<button @click="sendMessage">Send</button>
<ul>
<li v-for="msg in messages">{{ msg }}</li>
</ul>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
message: '',
messages: []
},
created: function() {
var socket = io.connect('http://localhost:5000');
socket.on('message', function(msg) {
console.log('Message: ' + msg.data);
});
socket.on('connect', function() {
console.log('Connected');
});
socket.on('disconnect', function() {
console.log('Disconnected');
});
},
methods: {
sendMessage: function() {
socket.emit('message', {data: this.message});
this.messages.push(this.message);
this.message = '';
}
}
});
</script>
</body>
</html>
确保Flask服务器正在运行,并且Vue.js页面可以连接到该服务器。在输入框中输入消息并点击"Send"按钮,消息将通过WebSocket发送到服务器,服务器将广播该消息给所有客户端,所有客户端的消息列表都会更新。
评论已关闭