京东6.18大促主会场领京享红包更优惠

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 7183|回复: 0

前端监听websocket消息并实时弹出(实例代码)

[复制链接]

22

主题

0

回帖

10

积分

新手上路

积分
10
发表于 2021-12-5 05:54:23 | 显示全部楼层 |阅读模式 来自 中国
本文默认您已掌握react生态开发的相关技术,并熟练应用umiJS的原则上,请继续!) U7 u! \8 X+ ?- f# J( _
项目需求:2 i8 _* T' i) ^$ Y' M( a6 b
2 F6 L" B; P) i3 v2 h7 ^2 K! d2 K
1、服务侧推送给消息给前端,前端需要展示在右下角
* ^& p2 t# c0 b7 `  o( f( C2、根据不同的消息类型,提供不同的操作按钮‘同意’、‘拒绝’等
' n' p, U) |$ k7 z5 ^" h. H代码设计:* N% e( A3 |! P
, V) ?# G* k5 ?! L( Z1 S) Z
1、使用websocket方式建立通道7 L: N: n6 P. r$ D' D
2、前端基于umi+antd+reconnecting-websocket.js开发
! n6 @5 m8 e! d5 w" B$ ~3、使用express+express-ws+mockjs建立websocket服务通道,模拟服务端推送消息4 r) l+ ], ^9 f0 j8 ]. n% E
运行效果:
- T8 n! O: h# S/ q7 o: ^
; Q% N8 K1 S; s8 G) D
/ J/ Q7 f  @) e( J1 X. R' ?3 S% v! Z

# L$ ^$ r3 B# J- s! f7 Q' x
; s: X" p! u8 S
使用方法:$ I, [  g$ J  D3 ^, P+ t
( d' H5 B2 q3 {. G/ t/ f
1、项目中已引入reconnecting-websocket.min.js,详见其官方文档
# A7 I8 j+ `0 o2 H! n8 U3 j, v2、登录成功后,接着调用websocket初始化:
  1. yield put({    type: 'websocket/init',    payload: {        authToken    }});
复制代码
核心代码:4 z+ k0 @  d' q- W; S+ w. Q' @
- p' W; a) i* J3 t
1、/service/websocket.js
  1. /** * 基于reconnecting-websocket库已引入 * 封装service文件 */class Websocket{   /**   * websocket逻辑   * 2021-10-28   */   constructor(){    this.websocket=null;    this.url='ws://127.0.0.1:30001/websocket-im';    this.options={      connectionTimeout: 5000,      maxRetries: 10,    };  }   init=()=>{    this.websocket = new ReconnectingWebSocket(this.url,[], this.options);  }   close=()=>{    this.websocket && this.websocket.close();  }   onMessage=(callback)=>{    this.websocket && this.websocket.addEventListener('message', (e) => {      callback&&callback(e)    });  } } const websocket = new Websocket(); // 初始化连接export function openWs() {  return websocket.init();} // 关闭连接export function closeWs() {  return websocket.close();} // 监听websocket消息export function onMessage() {  let deferred;  websocket.onMessage(function(e){    if(deferred) {        deferred.resolve(e)        deferred = null     }  });  return {    message() {      if(!deferred) {          deferred = {}          deferred.promise = new Promise(resolve => deferred.resolve = resolve)      }      return deferred.promise;    }  }}
复制代码
2、/model/websocket.js
  1. /** * 封装model文件 * moment、immutable、antd、nanoid组件请自行学习 */import {openWs,onMessage,closeWs} from 'services/websocket'import moment from 'moment'import { Map, fromJS } from 'immutable'import { notification } from 'antd'import nanoid from 'nanoid'; const initState = Map({   message:Map(), //收到的消息  });export default {  namespace: 'websocket',   state: initState,  subscriptions: {    setup({ dispatch, history }) {      dispatch({        type: 'listener'      });      return history.listen(({ pathname, query }) => {              });    },  },  effects: {     * listener({ payload }, { take, put, call }) {      while (true) {        const { type, payload } = yield take(['logout']);                // 监听退出系统,则关闭websocket        if (type === 'logout') {          // 关闭websocket          yield call(closeWs);          notification.destroy();          yield put({            type: 'clearAllMessage',             payload:{            }          });        }      }    },     // 启动websocket    * init ({      payload,    }, { put, call, select }) {      yield call(openWs);      const listener = yield call(onMessage);      yield put({type: 'receiveMsg', payload:{listener}});    },      // 接受消息    * receiveMsg ({        payload: {listener}    }, { call, select, put}) {        while(true){          const event = yield call(listener.message);           yield put({            type: 'progressMsg',             payload:{              msg:JSON.parse(event.data)            }          });                              }    },     // 统筹消息    * progressMsg ({        payload: {msg}    }, { call, select, put}) {       console.log(msg)            yield put({        type: 'addOneMessage',         payload:{          msg        }      });            },   },    reducers: {        addOneMessage(state, { payload:{msg} }) {         const msgId = nanoid()+'-'+moment().format('x');      return state.setIn(['message',msgId], fromJS({...msg,msgId}))     },     removeOneMessage(state, { payload:{msgId} }) {         return state.deleteIn(['message',msgId])     },     clearAllMessage(state, { payload:{} }) {         return state.setIn(['message'],Map())     },       },  }
复制代码
3、Notification组件封装,结构及代码
1 f/ s- n# `& S
 

3 v  Z) W- ?& m- Q! y) I(1)package.json
  1. {  "name": "Notification",  "version": "0.0.0",  "private": true,  "main": "./index.js"}
复制代码
(2) index.less
  1. .Notification{    .btns{        padding: 0;        margin: 15px 0 0 0;        list-style: none;        width: 100%;        display: flex;        justify-content: flex-end;        li{            margin-left: 10px;        }    }}
复制代码
(3)index.js
  1. /** * 右下角弹窗组件封装 */import React from 'react'import { injectIntl } from 'react-intl';import moment from 'moment'import { connect } from 'dva'import { notification } from 'antd';import Demo1 from './Demo1'import Demo2 from './Demo2' @injectIntl@connect(({  websocket, }) => ({   websocket}))export default class Notification extends React.Component {   componentWillReceiveProps(nextProps) {    const {websocket,dispatch,intl, intl: { formatMessage }} = nextProps;    let message=websocket.get('message');     message.forEach((note)=>{       let object=note.getIn(['object']);      let msgId=note.getIn(['msgId']);      let title=note.getIn(['title']);      let content=note.getIn(['content']);      let format = 'YYYY-MM-DD HH:mm:ss';      let time=note.getIn(['ts'])?moment(note.getIn(['ts']), 'x').format(format):moment().format(format);       switch (object) {        case 'demo1':          content=this.onClose(msgId)}                                        />;                                        break;        case 'demo2':          content=this.onClose(msgId)}          />;          break;        default:                                        break;                        }       notification.open({        message: {title} {time},        duration:30,        key: msgId,        description:content,        placement: 'bottomRight',        onClick: () => {                  },        onClose: () => {          this.onClose(msgId);        }      });    })   }   // 关闭消息  onClose=(msgId)=>{    const {dispatch} = this.props;    dispatch({      type:'websocket/removeOneMessage',      payload:{        msgId      }    })    return notification.close(msgId);  }    render(){    return(        null    )  }  }  Notification.propTypes = {  }
复制代码
(4)Demo1.js
  1. import React from 'react'import styles from './index.less' export default class NotificationSon extends React.Component {    render(){    const {note,intl:{formatMessage}} = this.props;    let content=note.getIn(['content']);     return(                  {content}
  2.         
  3.     )  }  } NotificationSon.propTypes = {  }
复制代码
(5)Demo2.js 
  1. import React from 'react'import styles from './index.less'import { config } from 'utils'import { Button } from 'antd'; const { defaultStyleSize } = config; export default class NotificationSon extends React.Component {   dealApproval=(type,data)=>{    const {dispatch,onClose} = this.props;    if(type=='refuse'){      console.log('拒绝')      onClose();    }else if(type=='agree'){      console.log('同意')      onClose();    }      }    render(){    const {note,intl:{formatMessage}} = this.props;    let content=note.getIn(['content']);     return(                  {content}
  2.          
  3. [list]            
  4. [*]               {this.dealApproval('agree',note.get('data'))}}>{formatMessage({id: 'Global.agree'})}            
  5. [*]               {this.dealApproval('refuse',note.get('data'))}}>{formatMessage({id: 'Global.refuse'})}         
  6. [/list]        
  7.     )  }  } NotificationSon.propTypes = {  }
复制代码
express模拟消息:* N% |/ T! Z6 R- S( x
' x8 s! A6 ^4 B- N) T
到此这篇关于前端监听websocket消息并实时弹出的文章就介绍到这了,更多相关websocket消息监听内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!
; \9 _' R3 i0 X, O+ z5 E% q
0 v! Z* B5 J/ x来源:http://www.jb51.net/html5/798933.html
8 C' m3 H$ z: \% _; m" K免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×

帖子地址: 

梦想之都-俊月星空 优酷自频道欢迎您 http://i.youku.com/zhaojun917
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|梦想之都-俊月星空 ( 粤ICP备18056059号 )|网站地图

GMT+8, 2025-11-11 02:22 , Processed in 0.040360 second(s), 23 queries .

Powered by Mxzdjyxk! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表