前端:注意一點,鏈接只能初始化、維持一個class,多個的話就是多個鏈接了
import { notification } from 'antd';
import {getUserName} from '@/utils/cookies';
import io from 'socket.io-client';
notification.config({
placement: 'bottomRight',
});
class websocket {
constructor() {
this.socket = '';
}
open(token) {
if (token) {
if (this.socket === '') {
this.socket = io('http://127.0.0.1:7001', { query: {token},transports: ['websocket'], reconnection: false, autoConnect: false});
}
if (!this.socket.connected) {
this.socket.open();
this.init()
}
}
}
close() {
this.socket.close();
this.socket.off('res', this.onMsg);
this.socket.off('connect');
}
init() {
this.socket.on('connect', () => {
console.log('已連接!');
this.socket.emit('chat', getUserName());
});
this.socket.on('res', this.onMsg)
}
onMsg(msg) {
notification['info']({
message: msg.title,
description: msg.content,
});
}
}
export default websocket
node端:egg-socket.io
1.config.default.js:連接、斷開、發送中間件
config.io = {
init: { }, // passed to engine.io
namespace: {
'/': {
connectionMiddleware: [ 'connection' ],
packetMiddleware: [ 'packet' ],
},
},
// 集羣模式下
// redis: {
// host: { redis server host },
// port: { redis server port },
// auth_pass: { redis server password },
// db: 0,
// },
};
2.連接、斷開中間件
根據token連接,斷開時去掉此在線用戶
module.exports = () => {
return async (ctx, next) => {
const jwtToken = ctx.helper.verifyToken(ctx.socket.handshake.query.token, ctx.app.config.jwtTokenSecret);
if (!jwtToken) {
return;
}
const { username } = await ctx.service.user.getUserById(jwtToken.id)
await next();
console.log('斷開!', username);
ctx.service.userInline.DeleteInlineKey(username);
};
};
3.連接成功之後,前端發送chat事件,後端把此用戶寫入在線用戶中
4.服務端發送消息到客戶端
4.1客戶端監聽res事件
this.socket.on('res', this.onMsg)
4.2 服務端發送res事件,攜帶信息
this.ctx.app.io.of('/').emit('res', sendMsg);