ant desgin pro 的項目中 封裝的 socket.js


const socket = {
  // websocketUrl: 'wss://www.xpms.cn:8080/websocket/', // socket監聽地址
  websocketUrl: 'wss://127.0.0.1:8080/websocket/', // socket監聽地址
  websocket: null, // websocket監聽對象
  isWebSocket: false, // 是否連接

  // 建立連接
  created: option => {
    socket.initWebSocket(option);
  },

  // 斷開連接
  destroyed: () => {
    if (socket && socket.websocket) {
      socket.websocket.close(); //離開路由之后斷開websocket連接
    }
  },

  // 初始化socket信息
  initWebSocket: option => {
    const { onMessage, onError, onClose, id } = option || {};
    //初始化weosocket
    // 取用戶信息,作為socketid
    let currentUser = JSON.parse(sessionStorage.getItem('currentUser'));
    if (!currentUser) return;
    // socket信息
    socket.websocket = new WebSocket(socket.websocketUrl + (id || currentUser.id));
    socket.websocket.onmessage = onMessage || socket.websocketonmessage;
    socket.websocket.onopen = socket.websocketonopen;
    socket.websocket.onclose = onClose || socket.websocketonclose;
    socket.websocket.onerror = onError || socket.websocketonerror;
  },

  // 監聽socket連接成功信息
  websocketonopen: () => {
    //連接建立之后執行send方法發送數據
    socket.isWebSocket = true;
    console.log('鏈接成功!');
  },

  // 監聽socket連接關閉信息
  websocketonclose: () => {
    console.log('鏈接關閉!');
  },

  // socket連接失敗重新建立連接
  websocketonerror: () => {
    //連接建立失敗重連
    socket.initWebSocket();
  },

  // 監聽接收消息
  websocketonmessage: e => {
    //數據接收
    console.log('redata', e.data);
  },

  // 發送消息
  websocketsend: data => {
    //數據發送
    // 如果未建立連接,則建立連接
    if (socket.isWebSocket) {
      socket.websocket.send(data);
    } else {
      console.log('請建立連接!');
    }
  },

  // 關閉連接
  websocketclose: e => {
    //關閉
    if (socket && socket.websocket) {
      socket.websocket.close();
    }
    socket.isWebSocket = false;
  },
};
export default socket;

 在頁面中進行調用寫業務邏輯

import React, { Component } from 'react';
import { Tag, message, notification } from 'antd';
import { connect } from 'dva';
import groupBy from 'lodash/groupBy';
import moment from 'moment';
import NoticeIcon from '../NoticeIcon';
import styles from './index.less';
import { router } from 'umi';
import Socket from '@/utils/socket/socket';
import { getPageQuery } from '@/utils/utils';
import { stringify } from 'querystring';

class GlobalHeaderRight extends Component {
  componentDidMount() {
    const { dispatch } = this.props;
    if (dispatch) {
      dispatch({
        type: 'global/fetchNotices',
      });
    }

    Socket.created({ onMessage: this.onSocketMsg, onClose: this.onClose, onError: this.onError });
  }

  onSocketMsg = e => {
    const { dispatch } = this.props;
    const msg = JSON.parse(e.data);
    if (dispatch) {
      dispatch({
        type: 'global/addNotices',
        payload: msg,
      });
    }
    if (msg) {
      let voice = document.getElementById('voice');
      voice.play();

      notification['info']({
        message: '新消息',
        description: msg.content,
      });
    }
    if (window.location.pathname !== '/audit') {
      dispatch({
        type: 'global/changeAuditRefush',
      });
    }
  };
  onError = e => {
    console.log('socke異常', e);
    // message.error('網絡異常');
    // sessionStorage.removeItem('currentUser');
    // sessionStorage.removeItem('token');
    // sessionStorage.removeItem('config');
    // const { redirect } = getPageQuery();
    // if (window.location.pathname !== '/user/login' && !redirect) {
    //   router.replace({
    //     pathname: '/user/login',
    //     search: stringify({
    //       redirect: window.location.href,
    //     }),
    //   });
    // }
  };
  onClose = e => {
    console.log('socke關閉', e);
    // message.error('網絡異常連接斷開,請重新登錄');
    // sessionStorage.removeItem('currentUser');
    // sessionStorage.removeItem('token');
    // sessionStorage.removeItem('config');
    // const { redirect } = getPageQuery();
    // if (window.location.pathname !== '/user/login' && !redirect) {
    //   router.replace({
    //     pathname: '/user/login',
    //     search: stringify({
    //       redirect: window.location.href,
    //     }),
    //   });
    // }
  };

  changeReadState = clickedItem => {
    const { id, message_type } = clickedItem;
    const { dispatch } = this.props;

    if (message_type == '3') {
      router.push('todo');
    }

    if (dispatch) {
      dispatch({
        type: 'global/changeNoticeReadState',
        payload: id,
      });
    }
  };
  handleNoticeClear = (title, key) => {
    const { dispatch } = this.props;
    message.success(`${'清空了'} ${title}`);

    if (dispatch) {
      dispatch({
        type: 'global/clearNotices',
        payload: key,
      });
    }
  };

  getNoticeData = () => {
    const { notices = [] } = this.props;
    if (notices.length === 0) {
      return {};
    }
    const newNotices = notices.map(notice => {
      const newNotice = { ...notice };

      if (newNotice.datetime) {
        newNotice.datetime = moment(notice.datetime).fromNow();
      }

      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }

      if (newNotice.extra && newNotice.status) {
        const color = {
          todo: '',
          processing: 'blue',
          urgent: 'red',
          doing: 'gold',
        }[newNotice.status];
        newNotice.extra = (
          <Tag
            color={color}
            style={{
              marginRight: 0,
            }}
          >
            {newNotice.extra}
          </Tag>
        );
      }

      return newNotice;
    });
    return groupBy(newNotices, 'message_type');
  };

  getUnreadData = noticeData => {
    const unreadMsg = {};
    Object.keys(noticeData).forEach(key => {
      const value = noticeData[key];

      if (!unreadMsg[key]) {
        unreadMsg[key] = 0;
      }

      if (Array.isArray(value)) {
        unreadMsg[key] = value.filter(item => !item.read).length;
      }
    });
    return unreadMsg;
  };

  render() {
    const { unreadCount, fetchingNotices, onNoticeVisibleChange, notices = [] } = this.props;
    const noticeData = this.getNoticeData();
    const unreadMsg = this.getUnreadData(noticeData);
    return (
      <>
        <audio id="voice" src="https://www.xpms.cn:8080/file/hotel/voice/new_msg.mp3" />
        <NoticeIcon
          className={styles.action}
          count={unreadCount}
          onItemClick={item => {
            this.changeReadState(item);
          }}
          loading={fetchingNotices}
          clearText={'清空了'}
          viewMoreText={'查看更多'}
          onClear={this.handleNoticeClear}
          onPopupVisibleChange={onNoticeVisibleChange}
          onViewMore={() => router.push('messageList')}
          clearClose
        >
          <NoticeIcon.Tab
            tabKey="1"
            count={unreadMsg[1]}
            list={noticeData[1]}
            title={'通知'}
            emptyText={'你已查看所有通知'}
            showViewMore
          />
          <NoticeIcon.Tab
            tabKey="2"
            count={unreadMsg[2]}
            list={noticeData[2]}
            title={'消息'}
            emptyText={'您已讀完所有消息'}
            showViewMore
          />
          <NoticeIcon.Tab
            tabKey="3"
            title={'待辦'}
            emptyText={'你已完成所有待辦'}
            count={unreadMsg[3]}
            list={noticeData[3]}
            showViewMore
          />
        </NoticeIcon>
      </>
    );
  }
}

export default connect(({ login, global, loading }) => ({
  currentUser: login.currentUser,
  collapsed: global.collapsed,
  fetchingMoreNotices: loading.effects['global/fetchMoreNotices'],
  fetchingNotices: loading.effects['global/fetchNotices'],
  notices: global.notices,
  unreadCount: global.unreadCount,
}))(GlobalHeaderRight);

  web socket中   的框架  國內流行

官網:  https://www.goeasy.io/cn/get-start.html     參考: https://blog.csdn.net/qq_29590623/article/details/87977859   參考: http://www.ruanyifeng.com/blog/2017/05/websocket.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM