1. 程式人生 > 實用技巧 >ant desgin pro 的專案中 封裝的 socket.js

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);