在網(wǎng)上找了一些服務(wù)端代碼
服務(wù)端
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
});
//我記錄客戶端的對(duì)象
var sockets = {};
var online = 0;
io.on('connection',function(socket) {
**
* 發(fā)送訂單數(shù)據(jù) //我的業(yè)務(wù)邏輯方法行瑞,可忽略
*/
socket.on('sendOrderMsg',function(obj){
var target = sockets[obj];
if(target != undefined){
target.emit("re_emit","ffffffffffffffffffffkkkkkkkkkkkkk")
}
})
/**
* 連接口注冊(cè)存入socket信息
*/
socket.on("register",function(obj){
sockets[obj] = socket;
});
socket.on("disconnect",function(obj){
})
});
/**
*監(jiān)聽3001端口
*/
http.listen(3001, function(){
console.log('listening on *:3001');
});
VUE端
全局引入socket颠悬,然后連接
//全局引入
import VueSocketIO from 'vue-socket.io'
Vue.use(new VueSocketIO({
debug: true,
// 服務(wù)器端地址
connection: 'http://socket.xxxxx.cn',
vuex: {
}
}))
在需要使用的地方,調(diào)用相應(yīng)的方法
我是在mounted方法中調(diào)用監(jiān)聽回調(diào)事件與注冊(cè)事件,這與我的業(yè)務(wù)邏輯有關(guān)
mounted() {
//調(diào)用監(jiān)聽回調(diào)事件,這與我的業(yè)務(wù)邏輯有關(guān)
this.sockets.listener.subscribe('re_emit', (data) => {
let audio = new Audio()
audio.src = orderAudio
audio.play();
})
//注冊(cè)事件座慰。這與我的業(yè)務(wù)邏輯有關(guān)
this.$socket.emit("register",localStorage.getItem("userId"))
}