==> 服务端促使客户端退出的小案例。
1 安装与配置
1.1 安装依赖包
npminstall egg-socket.ionpminstall 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=>{returnasync(ctx, next)=>{ ctx.socket.emit('res','connected!'); console.log('server socket connected');awaitnext();};};
app/io/middleware/packet.js
module.exports=app=>{returnasync(ctx, next)=>{ ctx.socket.emit('res','packet received!'); console.log('packet:', ctx.packet);awaitnext();};};
2 egg.js 中 websocket 使用
classAdminControllerextendsController{............asyncupdate(){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);}elseif(reqBody.type==='editPassword'){ res=await ctx.service.admin.editPassword(ctx.params.id, reqBody);}elseif(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=newSuccessResponse(null,'修改成功')}else{ ctx.body=newErrorResponse(null,'修改失败')}}............}
3 vue 中使用 websocket
main.js
import VueSocketIOfrom'vue-socket.io'const vueSocketIO=newVueSocketIO({ 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>......exportdefault{ 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中的使用.