Dva 中使用 WebSocket

基于dva,websocket, model,subscriptions, service. 能够接受服务器消息,向服务器发送消息,主动断开,可处理异常断开的例子.

1.设置modal

import * as service from '../services/websocket'
 
export default {
    namespace: 'websocket',
    state: {
        messages: undefined,
        client_id: undefined,
    },
    subscriptions: {
        watchWebSocket({dispatch, history}) {
            return history.listen(({pathname}) => {
                dispatch({type: 'open'});
            });
        }
    },
    effects: {
        * open({payload}, {put, call}) {
            //wss://echo.websocket.org
            const config = {url: 'wss://echo.websocket.org', user_name: 'xxx', user_id: 1, room_id: 999};
            // service.watchList(config, (data) => {
            //     dispatch({type: data.type, payload: data});
            // });
            const {data} = yield call(service.watchList, config);
            console.log('result', data);
        },
        * message({payload}, {put, call}) {
            console.log('message', payload);
            yield put({type: 'messageSuccess', payload: payload.client_id});
        },
        * send({payload}, {put, call}) {
            yield call(service.send, {config: {url: 'wss://echo.websocket.org'}, data: payload});
        },
    },
 
    reducers: {
        openSuccess(state, action) {
            //client_id:1
            return {...state, ... action.payload}
        },
        messageSuccess(state, action) {
        //messages{type:'message',data:{....}}
            return {...state, ... action.payload}
        },
    },
}

2. 连接后端通信service

let websocket = undefined;
function getWebsocket(url) {
    console.log('websocket client', websocket);
    if (!websocket) {
        websocket = new WebSocket(url);
    }
    return websocket;
}
 
export async function watchList(config, cb) {
    const client = getWebsocket(config.url);
    client.onopen = () => {
        client.send(JSON.stringify({type: 'login', ...config}));
    };
    // return client.onmessage = (data) => {
    //     cb(data);
    // };
 
    client.onmessage = (evt) => {
        const data = JSON.parse(evt.data);
        if (data) {
            switch (data.type) {
                case 'ping':
                    client.send('{"type":"pong"}');
                    // cb(data);
                    break;
                case 'login':
                case 'message':
                    // cb(data);
                    new Promise(function (resolve, reject) {
                        return resolve({data});
                    });
                    break;
                // 用户退出 更新用户列表
                case 'logout':
                    break;
            }
        }
    };
}
 
 
export async function send(config, data) {
    console.log('send', data);
    const websocket = getWebsocket(config.url);
    websocket.send(JSON.stringify(data));
}
 
export async function logout(config, code, reason) {
    const websocket = getWebsocket(config.url);
    websocket.close(code, reason);
}

subscriptions里面的在初始化的时候都会执行一下,history是dva提供给你的,你在service自己封装一下提供对socket时间监听的接口解可以了。

service里面:

export function listen(action) {
  socket.on('message', (data) => {
    action(data);
  });
}

subscriptions里面:

socketMessage({ dispatch }) {
  return service.listen((data) => {
    dispatch({ type: 'your action', payload: data });
  });
}

···

你可能感兴趣的:(Dva 中使用 WebSocket)