The front end listens to websocket messages and pops them up in real time (example code)

Time:2022-1-13

This article assumes that you have mastered the relevant technologies of react ecological development and skillfully applied umijs. In principle, please continue!

Project requirements:

1. The service side pushes messages to the front end, which needs to be displayed in the lower right corner
2. Different operation buttons such as “agree” and “reject” are provided according to different message types

Code design:

1. Establishing channels using websocket
2. The front end is based on UMI + antd + reconnecting websocket JS development
3. Use express + Express WS + mockjs to establish a websocket service channel to simulate the push message of the server

Operation effect:

usage method:

1. Reconnecting websocket. Has been introduced into the project Min.js, see its official document for details

2. After successful login, call websocket to initialize:


yield put({
    type: 'websocket/init',
    payload: {
        authToken
    }
});

Core code:

1、/service/websocket.js

/**
 *The reconnecting websocket library has been introduced
 *Encapsulating service files
 */
class Websocket{
 
  /**
   *Websocket logic
   * 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();
 
//Initialize connection
export function openWs() {
  return websocket.init();
}
 
//Close connection
export function closeWs() {
  return websocket.close();
}
 
//Listening for websocket messages
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

/**
 *Encapsulating model files
 *Please learn the moment, immutable, antd and nanoid components by yourself
 */
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(), // received message
  
});
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']);
        
        //If the listener exits the system, close the websocket
        if (type === 'logout') {
          //Close websocket
          yield call(closeWs);
          notification.destroy();
          yield put({
            type: 'clearAllMessage', 
            payload:{
            }
          });
        }
      }
    },
 
    //Start websocket
    * init ({
      payload,
    }, { put, call, select }) {
      yield call(openWs);
      const listener = yield call(onMessage);
      yield put({type: 'receiveMsg', payload:{listener}});
    }, 
 
    //Accept message
    * receiveMsg ({
        payload: {listener}
    }, { call, select, put}) {
        while(true){
          const event = yield call(listener.message);
 
          yield put({
            type: 'progressMsg', 
            payload:{
              msg:JSON.parse(event.data)
            }
          });
          
            
        }
    },
 
    //Overall information
    * 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 component encapsulation, structure and code

 

(1)package.json


{
  "name": "Notification",
  "version": "0.0.0",
  "private": true,
  "main": "./index.js"
}

(2) index.less


.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

/**
 *Pop up window assembly package at the lower right corner
 */
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=<Demo1
						dispatch={dispatch}
						intl={intl}
						note={note}
						onClose={()=>this.onClose(msgId)}
					/>;
					break;
        case 'demo2':
          content=<Demo2
            dispatch={dispatch}
            intl={intl}
            note={note}
            onClose={()=>this.onClose(msgId)}
          />;
          break;
        default:
					break;
			}
 
      notification.open({
        message: <span>{title} <small>{time}</small></span>,
        duration:30,
        key: msgId,
        description:content,
        placement: 'bottomRight',
        onClick: () => {
          
        },
        onClose: () => {
          this.onClose(msgId);
        }
      });
    })
 
  }
 
  //Close message
  onClose=(msgId)=>{
    const {dispatch} = this.props;
    dispatch({
      type:'websocket/removeOneMessage',
      payload:{
        msgId
      }
    })
    return notification.close(msgId);
  }
  
  render(){
    return(
        null
    )
  }
  
}
 
 
Notification.propTypes = {
  
}

(4)Demo1.js


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(
        <div className={styles.Notification}>
          <div>{content}</div>
        </div>
    )
  }
  
}
 
NotificationSon.propTypes = {
  
}

(5)Demo2.js 

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 ('reject ')
      onClose();
    }else if(type=='agree'){
      console. Log ('agree ')
      onClose();
    }
    
  }
  
  render(){
    const {note,intl:{formatMessage}} = this.props;
    let content=note.getIn(['content']);
 
    return(
        <div className={styles.Notification}>
          <div>{content}</div>
          <ul className={styles.btns}>
            <li>
              <Button style={{ marginLeft: '12px' }} type={'primary'} size={defaultStyleSize}  onClick={() => {this.dealApproval('agree',note.get('data'))}}>{formatMessage({id: 'Global.agree'})}</Button>
            </li>
            <li>
              <Button style={{ marginLeft: '12px' }} type={'danger'} size={defaultStyleSize}  onClick={() => {this.dealApproval('refuse',note.get('data'))}}>{formatMessage({id: 'Global.refuse'})}</Button>
            </li>
          </ul>
        </div>
    )
  }
  
}
 
NotificationSon.propTypes = {
  
}

Express simulation message:

This is the end of this article about the front-end monitoring websocket messages and popping up in real time. For more information about websocket message monitoring, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!