==> 服务端促使客户端退出的小案例。
1 安装与配置
1.1 安装依赖包
npm install egg-socket.io
npm install vue-socket.io
1.2 配置 egg.js
config/config.default.js
module.exports = appInfo => {
const config = exports = {};
......
config.security = {
csrf: {
enable: false,
},
};
config.cors = {
origin: '*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
};
config.io = {
init: {},
namespace: {
'/': {
connectionMiddleware: [ 'connection' ],
packetMiddleware: [ 'packet' ],
}
}
};
return {
...config
};
}
config/plugin.js
module.exports = {
......
......
io: {
enable: true,
package: 'egg-socket.io',
},
};
app/io/middleware/connection.js
module.exports = app => {
return async (ctx, next) => {
ctx.socket.emit('res', 'connected!');
console.log('server socket connected');
await next();
};
};
app/io/middleware/packet.js
module.exports = app => {
return async (ctx, next) => {
ctx.socket.emit('res', 'packet received!');
console.log('packet:', ctx.packet);
await next();
};
};
2 egg.js 中 websocket 使用
class AdminController extends Controller {
......
......
async update() {
const { ctx, app } = this;
const nsp = app.io.of('/');
let res;
const reqBody = ctx.request.body;
if (reqBody.type === 'rename') {
res = await ctx.service.admin.rename(ctx.params.id, reqBody);
} else if (reqBody.type === 'editPassword') {
res = await ctx.service.admin.editPassword(ctx.params.id, reqBody);
} else if (reqBody.type === 'editStatus') {
res = await ctx.service.admin.editStatus(ctx.params.id, reqBody);
if (res) {
if (reqBody.userStatus === 2 || reqBody.userStatus === 3) {
nsp.emit('logout', { msg: 'logout', id: ctx.params.id });
}
}
}
if (res) {
ctx.body = new SuccessResponse(null, '修改成功')
} else {
ctx.body = new ErrorResponse(null, '修改失败')
}
}
......
......
}
3 vue 中使用 websocket
main.js
import VueSocketIO from 'vue-socket.io'
const vueSocketIO = new VueSocketIO({
debug: true,
connection: 'http://127.0.0.1:7001',
})
vueSocketIO.io.on('connect', () => {
console.log('socket connect from main.js');
});
Vue.use(vueSocketIO)
home.vue
<script>
......
export default{
sockets: {
connect: function() {
console.log("socket connect from HOME page");
},
logout: function(data) {
console.log("wesocket-logout", data);
if (data.id === sessionStorage.getItem("userId")) {
this.$notify.error({
title: "您的账号已被停用/注销/删除!"
});
console.log("我退出了");
this.logout();
}
}
},
data(){...}
}
</script>
4 参考文献
[1] vue-socket.io使用教程与踩坑记录.
[2] egg-socket在egg中的使用.