(1)基础配置和常用方法请看vue-Socket.io的使用(1)
(2)nodeJS+vue+Socket.io聊天室实例
node-Js文件例子
var http = require('http');
var app = http.createServer(function(req, res) {
res.end(data)
})
console.log('app服务器开启成功');
//引入socket.io
var io = require('socket.io')(app)
//connection为自带的方法,类似生命周期里面的创建,连接后就会触发
io.on("connection", function(socket) {
console.log('一个用户与服务器建立连接', socket.handshake.query.id.toString())
socket.join(socket.handshake.query.id.toString());
//服务器获取客户端广播的数据
socket.on('news', function(data) {
for (let z = 0; z < data.newForMyApproval.length; z++) {
io.to(data.newForMyApproval[z].toString()).emit('newForMyApproval', '增加了一条审批') //通知分组内所有的用户
}
for (let i = 0; i < data.newCcToMe.length; i++) {
io.to(data.newCcToMe[i].toString()).emit('newCcToMe', '增加了一条抄送') //通知分组内所有的用户
}
})
// 接收到消息页的消息
socket.on("userChat", function(data) {
io.to(data.receiveNews.toString()).emit('newNews', data)
})
// 当关闭连接后触发 disconnect 事件
socket.on('disconnect', function() {
console.log(socket.handshake.query.id.toString(), '与服务器断开连接');
});
})
app.listen(3120)
Main.js
import VueSocketio from 'vue-socket.io';
if (JSON.parse(localStorage.getItem("USERNAMEID"))) { //判断本地是否有存用户id数据
Vue.use(new VueSocketio({
debug: true, //开发环境看socket.io的配置,开发结束改为false
connection: '127.0.0.1:3120' + '?id=' + JSON.parse(localStorage.getItem("USERNAMEID")).id,
options: {
autoConnect: false//默认true,设为false不会全局引入socket
},
})) //connection为项目端口位置,"+"?id的内容为向socket.io传递连接用户的数据
}
Vue页面引用(sockets:{}与methods:{}平级)
mounted() {
this.$socket.open();//局部引入socket
},
beforeDestroy() {
this.$socket.close();//退出组件时关闭socket
},
sockets: {
//断开重连
reconnect(data) {
console.log("第几次重新连接", data);
},
// socket传进一条审批
newForMyApproval(msg) {
let data = this.$store.state.Advanced.forMyApproval + 1;
console.log(msg);
this.$store.dispatch("FETCH_forMyApproval", data);
},
// socket传进一条抄送
newCcToMe(msg) {
let data = this.$store.state.Advanced.ccToMe + 1;
console.log(msg);
this.$store.dispatch("FETCH_ccToMe", data);
},
// socket接收到其他用户传递的消息
newNews(data) {
if (this.$route.path != "/information") {
this.$store.dispatch(
"FETCH_newspageNumber",
this.$store.state.Advanced.newspageNumber + 1
);
}
},
//获取当前在线用户的列表
newUserMan(data){
this.$store.dispatch("FETCH_newUserManArr",data);
}
},
网友评论