WebSocket客户端

全局消息监听

  • 所有全局的消息监听都在这里
  • 在main.ts中全局注册onMessageList
import Websocket from '/@/utils/websocket';
const app = createApp(App);
// 全局websocket
const onMessageList: Array<Function> = [];
app.provide('onMessageList', onMessageList);
const onMessage = (event: any) => {
    onMessageList.forEach((f) => {
        f.call(null, event);
    });
};
Websocket(onMessage);
  • 在文件:src/utils/websocket.ts 中处理消息
    socket.onmessage = function (event) {
        isActive = true;
        // console.log('WebSocket:收到一条消息', event.data);
        let isHeart = false;
        const message = JSON.parse(event.data);
        if (message.event === 'ping') {
          isHeart = true;
        }
        // 例如系统自带通知私信
        if (message.event === 'notice') {
          noticeStoreAct.setMessages(message.data)
          return;
        }
        //更多全局消息在此处添加
        if (message.event === '消息事件') {
          //处理代码......
          return;
        }
        if (onMessage && !isHeart) {
          onMessage.call(null, event);
        }
        heartCheck.reset().start();
      };

WebSocket服务端

  • 服务端可通过libWebsocket.SendToUser(userId, response)libWebsocket.SendToAll(response)方法把消息发送个指定用户或所有用户。
    可参考系统中自带消息websocket通知示例,单添加通知或私信时可发送给所有人或指定的私信人员:
func (s *sSysNotice) Add(ctx context.Context, req *model.SysNoticeAddReq) (err error) {
    err = g.Try(ctx, func(ctx context.Context) {
        data := do.SysNotice{
            Title:     req.Title,
            Type:      req.Type,
            Tag:       req.Tag,
            Content:   req.Content,
            Remark:    req.Remark,
            Receiver:  req.Receiver,
            Sort:      req.Sort,
            Status:    req.Status,
            CreatedBy: req.CreatedBy,
        }
        var rows sql.Result
        rows, err = dao.SysNotice.Ctx(ctx).Insert(data)
        liberr.ErrIsNil(ctx, err, "添加失败")
        data.Id, err = rows.LastInsertId()
        liberr.ErrIsNil(ctx, err, "获取ID失败")
        response := &libWebsocket.WResponse{
            Event: "notice",
            Data:  data,
        }
        if req.Type == consts.SysLetterType {
            //系统私信
            if len(req.Receiver) > 0 {
                for _, id := range req.Receiver {
                    libWebsocket.SendToUser(id, response)
                }
            }
        } else {
            //系统通知
            libWebsocket.SendToAll(response)
        }
    })
    return
}
  • 消息也可通过事件绑定处理器,只需要在注册消息路由中绑定对应消息事件名称及方法,例如绑定一个ping事件:

作者:管理员  创建时间:2024-05-07 11:06
最后编辑:管理员  更新时间:2024-06-14 15:58