首先搭建一个Egg项目,在终端输入以下命令
$ mkdir egg-socket
$ cd egg-socket
$ npm init egg --type=simple//之后配置文件,一路回车即可
$ npm i
打开vscode,在当前项目目录下安装egg-socket.io
$ npm i egg-socket.io --save
配置插件
// {app_root}/config/plugin.js
'use strict';
/** @type Egg.EggPlugin */
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
io : {
enable: true,
package: 'egg-socket.io',
},
};
//{app_root}/config/config.${env}.js
config.io = {
init: {}, // passed to engine.io
namespace: {
'/': {
connectionMiddleware: ['connection'],//连接中间件
packetMiddleware: [],//加密等处理
},
},
};
在Egg项目中创建出目录
app/io/controller
app/io/middleware
app/middleware
在app/io/controller中创建nsp.js文件,写入以下代码
'use strict'
const { Controller } = require('egg')
class NspController extends Controller {
async index() {
const { ctx, app } = this;
const message = ctx.args[0];
await ctx.socket.emit('res', `Hi! I've got your message: ${message}`);
}
}
module.exports = NspController;
在app/io/middleware下创建connection.js,写入以下代码
// {app_root}/app/io/middleware/connection.js
module.exports = app => {
return async (ctx, next) => {
ctx.socket.emit('res', 'connected!');
await next();
// execute when disconnect.
console.log('disconnection!');
};
};
设置路由
// socket.io
io.of('/').route('server', io.controller.nsp.index);
在浏览器中输入网址:vue-socket.io - npm (npmjs.com)
根据指令,在Vue项目目录里下载
npm install vue-socket.io --save
将引入写到main.js文件里
//连接websocket
import VueSocketIO from 'vue-socket.io'
Vue.use(new VueSocketIO({
debug: true,
connection: 'ws://localhost:7001',
}))
new Vue({
sockets: {
connect: function() {
console.log('socket connected')
},
customEmit: function(data) {
console.log(`this method was fired by the socket server. eg: io.emit
("customEmit",${ data })`)
}
},
router,
store,
render: h => h(App)
}).$mount('#app')
|