egg-socket和socket.io-client完成前后端socket链接

前端:注意一点,链接只能初始化、维持一个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,
    // },
  };

egg-socket和socket.io-client完成前后端socket链接_第1张图片

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);

 

 

 

 

 

你可能感兴趣的:(随笔&笔记,node,egg,socket)