9-8
Egg服务端
首先搭建一个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,目的是看下是否连接到egg
// {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!');
};
};
在app/io/middleware下创建packet.js,目的是对消息进行加密或检验处理
module.exports = app => {
return async(ctx, next) => {
ctx.socket.emit('res', '中间件packet收到消息');
console.log('packet:', ctx.packet);
await next();
};
};
设置路由
// socket.io
io.of('/').route('server', io.controller.nsp.index);
Vue客户端
安装vue,这里用的vue2
//新开一个终端
npm install -g @vue/cli
vue create vuename
npm run serve
在浏览器中输入网址: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')
嗯?怎么两边都是对的就是连不上呢?
(68条消息) egg-socket.io搭配socket.io-client的坑_是吱吱的博客-CSDN博客
嗯,我也是2.1.1
(68条消息) Eggjs+Vue集成全双工服务(Socket.io)_yeCaofire的博客-CSDN博客
这篇博客简直救命,连上了铁汁
修改后的main.js是这样的,别忘了下载socket.io-client@2.1.1
import ClientSocketIO from 'socket.io-client'
import Vue from 'vue'
import VueSocketIO from 'vue-socket.io'
import App from './App.vue'
//import router from './router'
//import store from './store'
Vue.use(
new VueSocketIO({
debug: true,
// ClientSocketIO(url, option), option中可以配置重连时间,超时时间设定,重连间隔等
connection: ClientSocketIO('http://127.0.0.1:7001', { transports: ['websocket'] }),
vuex: {
//store,
actionPrefix: 'SOCKET_'
}
})
)
new Vue({
//router,
//store,
render: h => h(App),
}).$mount('#app')
但是我们前端还没有给后端发消息 ,后端也没给前端发消息。所以我修改App.vue为
<template>
<div>
<div>
<button @click="sendSocketMsg">发socket信息</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
text: "这是首页"
};
},
mounted() {
//添加socket事件监听
/**
* 当服务端和客户端连接成功时,服务端会监听到connection和connect事件,
* 客户端会监听到connect事件,断开连接时服务端对应到客户端的socket与
* 客户端均会监听到disconcect事件。
*/
},
sockets: {
connect: function() {
console.log('socket connected...')
},
res: function(message) {
console.log('response from server: ', message)
},
disconnect: function() {
console.log('disconnect!')
},
},
methods: {
sendSocketMsg() {
//向服务端发送消息
this.$socket.emit("index", { name: "张三" });
//接收服务端相对应的webdata数据
}
}
};
</script>
9-11
egg直到今天才发现问题,消息只传到middleware就不往controller传了,最后发现名字没有统一
//router
io.of('/').route('index', io.controller.nsp.index);//index一定要和前端对应起来
//index方法
async index() {
const { ctx } = this;
const message = ctx.args[0];
console.log(message) //woc我拿到了啊啊啊啊啊啊
await ctx.socket.emit('res', `Hi! I've got your message:${message} `);
}
至此,收发消息成功
最后附上曾经很有帮助的csdn资料们
(56条消息) 每日JavaScript之socket.io实现聊天室_tcap99的博客-CSDN博客
WebSocket学习(一)——基于socket.io实现简单多人聊天室 - SegmentFault 思否
(68条消息) vue中使用vue-socket.io_a8725585的博客-CSDN博客_vue-socket.io
(68条消息) egg框架(通过egg-socket.io建立即时通讯服务,实现聊天功能)_逆风丶大魔王的博客-CSDN博客
(68条消息) Vue框架(使用vue-socket.io-extended实现聊天功能)_逆风丶大魔王的博客-CSDN博客_vue-socket.io-extended