1.vue
<template>
<div class="socket"></div>
</template>
<script>
import VueSocketIO from "vue-socket.io";
import SocketIO from "socket.io-client";
Vue.use(new VueSocketIO({
connection: SocketIO("http://127.0.0.1:8000/mysocket", {
autoConnect: false // 自动连接
}),
extraHeaders: { "Access-Control-Allow-Origin": "*" }
}));
export default {
name: "socket",
props: {},
components: {},
data() {
return {
};
},
computed: {
},
created() {
// 连接socket
this.$socket.open();
},
sockets: {
// 后台数据推送时间,自定义
acceptData: function (data) {
console.log(data);
},
connect: function() {
console.log("连接成功");
},
connecting: function() {
console.log("正在连接");
},
disconnect: function() {
console.log("断开连接");
},
connect_failed: function() {
console.log("连接失败");
},
error: function() {
console.log("错误发生,并且无法被其他事件类型所处理");
},
reconnect_failed: function() {
console.log("重连失败");
},
reconnect: function() {
console.log("成功重连");
},
reconnecting: function() {
console.log("正在重连");
}
},
methods: {
sendHeartbeat() {
// 发送心跳包
this.$socket.emit("heartbeat");
},
sendData(data) {
// 发送数据
this.$socket.emit("update_data", data);
}
},
filters: {
},
watch: {
},
destroyed() {
// 断开socket
if (this.$socket) {
this.$socket.close();
}
}
};
</script>
2.python
import time
from flask import Flask, request
from flask_cors import CORS
from flask_socketio import SocketIO, Namespace
app = Flask(__name__)
# 跨域
CORS(app, supports_credentials=True, cors_allowed_origins='*')
class SendData(Namespace):
def __init__(self, namespace=None):
super(SendData, self).__init__(namespace)
def on_connect(self):
print("连接成功")
def on_connecting(self):
print("正在连接")
def on_disconnect(self):
print("断开连接")
def on_connect_failed(self):
print("连接失败")
def on_error(self):
print("错误发生,并且无法被其他事件类型所处理")
def on_reconnect_failed(self):
print("重连失败")
def on_reconnect(self):
print("成功重连")
def on_reconnecting(self):
print("正在重连")
def on_update_data(self, data):
# 前端数据上发
print(data)
def on_heartbeat(self):
print(request.sid)
def send_data(self, data, room):
while True:
self.emit(event='acceptData', data=data, room=room)
time.sleep(10)
if __name__ == '__main__':
socket_io = SocketIO(app, cors_allowed_origins='*')
socket_io.on_namespace(SendData('/mysocket', ))
socket_io.run(app=app, host='0.0.0.0', port=6200)