监听全局消息

注意:

  • 如果使用nginx必须增加http 1.1 协议支持 否则无法接收消息通知

使用场景

    1. 跨多端消息通知 (例如手机发出通知消息,电脑的浏览器接收消息)
    1. 前端接收后端服务的通知消息. (后台服务器发送消息给电脑浏览器消息)

函数定义

  • 前端函数定义:

    export class Common {
    ...
      /**
       * 监听服务器消息
       * 一般用于全局监听整个平台的消息
       * @param msgId 消息唯一ID   接收sendServerMsg 发出消息唯一ID的消息
       * @param callback 回调函数
       * @param timeout 消息的存活的时间后释放. 默认 300秒 
       * @return 返回消息服务对象实例
       */
      public static onServerMsg(msgId: string, callback: ServerMsgCallback, timeout: number = 300)
    
      /**
      * 向服务器发生消息
      * @param msgId   消息唯一ID 
      * @param msg  消息常量值
      */
      public static sendServerMsg(msgId: string, msg: string)
  • 后端服务器函数定义:

public class SseEmitterUtil {
...
    /**
     * 给指定消息id发送信息
     * @param msgId 消息唯一ID 
     * @param message 消息内容
     */
    public static void sendMessage(String msgId, String message);
...

}

例子: 手机上传图片后通知电脑端的浏览器回显图片

  • 手机端
function btnOk_onClickScript(cxt:ScriptContext,btn:Button){
    let cmps=btn.getPage().components;
    let msgId=btn.getPage().getParamValue('msgId')
    Common.get(`${Common.getContextPath()}/core/sse/live/${msgId}`, {}, (res) => {
        if (res.state == RetState.ERROR) {
            Common.errorMsg("上传页面已经过期.");
        } else {
            Common.sendServerMsg(msgId,cmps.UploadCmp1.getValue())
        }
    })
}
...
}
  • 电脑端
    /**
     * 显示手机上传的二维码
     */
    showBarCode() {
        let that = this,
            barFormElemId = `barcode${this.btnMobileId}`;
        this.barElemId = `barcodeValue${this.btnMobileId}`,
            this.formindex = Common.Form({
                type: FormType.page,
                id: barFormElemId,
                area: ['457px', '530px'],
                content: this.getBarCodeHtml(),
                title: '微信/企微/手机浏览器扫描二维码上传文件',
                openAnim: FormAnimType.fadeIn,
                closeAnim: FormAnimType.fadeOut,
                onSuccess() {
                    let title = $(top.document.body).find('.layui-logo-title').html() || '',
                        val = EncryptUtils.Base64Encode(that.getValue() || ''),
                        msgId = Common.generalGUID(),
                        url = Common.getFullUrl(`${Common.getContextPath()}/manager/coremodelshow/?modelId=Z6568BED6BC649CF9A240D8DF237473C&title=${EncryptUtils.Base64Encode(title)}&encrypt=${that.isEncrypt}&tokenId=${Common.getTokenId()}&msgId=${msgId}&value=${val || ''}`)
                    Common.QrCode(url, that.barElemId, 400, 400);
                    that.sse.push(
                        Common.onServerMsg(msgId, (data) => {
                            that.setValue(data);
                            console.info(data);
                        })
                    )
                }
            });
    }
作者:texbox  创建时间:2023-08-11 15:50
最后编辑:texbox  更新时间:2024-04-26 09:11