Browse Source

websocket conn status store

master
tangmingyou 4 years ago
parent
commit
a73de9a458
  1. 2
      src/api/http.js
  2. 1278
      src/api/proto.js
  3. 64
      src/api/websocket.js
  4. 11
      src/pages/login/login.jsx
  5. 23
      src/store/conn.js
  6. 6
      src/store/index.js

2
src/api/http.js

@ -45,7 +45,7 @@ const fetch = function (method, url, params) {
}) })
} }
if (res.statusCode !== 200 || !res.data || res.data.code !== 200) { if (res.statusCode !== 200 || res.data.code) { // || !res.data
return reject(res.data || {}); return reject(res.data || {});
} }
resolve(res.data); resolve(res.data);

1278
src/api/proto.js

File diff suppressed because it is too large Load Diff

64
src/api/websocket.js

@ -1,16 +1,23 @@
import { api } from '@/api/proto' import proto from '@/api/proto';
import { showRedPackage } from '@tarojs/taro-h5';
const { api } = proto
const websocket = { const websocket = {
conn: null, conn: null,
opMap: {},
state: 0, // 0未初始,1打开,2关闭 state: 0, // 0未初始,1打开,2关闭
seq: 1, // 消息序号 seq: 1, // 消息序号
init(token, opMap) { offset: 0,
if (opMap) { failOp: 0,
this.opMap = opMap; opPathMap: {},
} nameOpMap: {},
init(token, { offset, failOp, opPathMap, nameOpMap }) {
this.offset = offset || 0;
this.failOp = failOp;
this.opPathMap = opPathMap || {};
this.nameOpMap = nameOpMap || {};
// window.proto = proto;
// websocket test // websocket test
const ws = new WebSocket("ws://localhost:9999/api/conn/ws") const ws = new WebSocket("ws://localhost:9999/api/conn/ws")
this.conn = ws this.conn = ws
console.log(this) console.log(this)
@ -19,39 +26,68 @@ const websocket = {
// 连接后立即认证连接 // 连接后立即认证连接
const req = api.ReqIdentity.create({ token }) const req = api.ReqIdentity.create({ token })
// const reqBuffer = api.ReqIdentity.encode(req).finish() // const reqBuffer = api.ReqIdentity.encode(req).finish()
this.send(req) this.send(req, res => {
console.log('call1:', res)
}, err => {
console.log('call2:', err)
})
} }
ws.onmessage = (e) => { ws.onmessage = (e) => {
console.log('msg:', e.data) console.log('msg:', e.data)
const wrap = api.ProtoWrap.decode(new Uint8Array(e.data)) const wrap = api.ProtoWrap.decode(new Uint8Array(e.data))
const res = api.ResIdentity.decode(wrap.body) // 解码响应体
const opPath = this.opPathMap[wrap.op]
if (!opPath) {
console.log('res op not exists!', wrap.op)
return
}
const res = proto[opPath[0]][opPath[1]].decode(wrap.body)
// const res = api.ResIdentity.decode(wrap.body)
console.log(wrap, res)
if (wrap.seq !== 0) { if (wrap.seq !== 0) {
// 对应请求callback // 对应请求callback
const waitCall = this.waitCall[wrap.req] const waitCall = this.waitCall[wrap.seq];
delete this.waitCall[wrap.seq];
console.log(waitCall, this.waitCall);
if (waitCall) { if (waitCall) {
waitCall.onRes(res) if (wrap.op === failOp) {
waitCall.onFail(res, wrap);
} else {
waitCall.onRes(res, wrap);
}
return; return;
} }
} }
// 找消息类型的listen执行 // 找消息类型的listen执行
const listener = this.msgListener[wrap.op] const listener = this.msgListener[wrap.op];
if (listener) { if (listener) {
listener(res) listener(res)
return;
} }
// console.log(wrap.op, res) console.log('no handler msg:', wrap.op, res)
} }
ws.onerror = (a, b, c) => { ws.onerror = (a, b, c) => {
console.log('error:', a, b, c) console.log('error:', a, b, c)
// var interval = setInterval(() => {
// this.reconnect();
// }, Math.random() * 3);
} }
ws.onclose = e => { ws.onclose = e => {
console.log('close', e) console.log('close', e)
} }
}, },
reconnect() {
},
waitCall: {}, // 等待响应的 callback 列表 waitCall: {}, // 等待响应的 callback 列表
send(msg, resCall, errCall) { send(msg, resCall, errCall) {
let typeUrl = msg.constructor.getTypeUrl();
const idx = typeUrl.lastIndexOf("/");
typeUrl = idx === -1 ? typeUrl : typeUrl.substring(idx + 1);
const op = this.nameOpMap[typeUrl];
console.log(typeUrl, op);
const msgBufer = msg.constructor.encode(msg).finish(); const msgBufer = msg.constructor.encode(msg).finish();
const wrap = api.ProtoWrap.create({ ver: 1, op: 13578 + 3, seq: this.seq++, body: msgBufer }); const wrap = api.ProtoWrap.create({ ver: 1, op: op, seq: this.seq++, body: msgBufer });
const wrapBuffer = api.ProtoWrap.encode(wrap).finish(); const wrapBuffer = api.ProtoWrap.encode(wrap).finish();
this.conn.send(wrapBuffer); this.conn.send(wrapBuffer);
if (resCall) { if (resCall) {

11
src/pages/login/login.jsx

@ -5,6 +5,7 @@ import Taro from '@tarojs/taro';
//import { Form, Input, TextArea, Cell, Button, Row, Col, Image } from '@nutui/nutui-react-taro'; //import { Form, Input, TextArea, Cell, Button, Row, Col, Image } from '@nutui/nutui-react-taro';
import ws from '@/api/websocket' import ws from '@/api/websocket'
import './login.scss' import './login.scss'
import { fetchOpMap } from '@/api/api'
/* /*
登录 -> 大厅 -> 新桌面 -> 进桌面 -> profile(弹窗) 登录 -> 大厅 -> 新桌面 -> 进桌面 -> profile(弹窗)
@ -39,7 +40,15 @@ function Login(props, ref) {
const handleSubmit = () => { const handleSubmit = () => {
console.log('submit', state) console.log('submit', state)
const token = "AgOjcdf3goeYDX3lwWWwkXtVpcrL-l2rX8csrRKgs3_-BC3JOx0l6nZU0MV25eIn" const token = "AgOjcdf3goeYDX3lwWWwkXtVpcrL-l2rX8csrRKgs3_-BC3JOx0l6nZU0MV25eIn"
ws.init(token) fetchOpMap()
.then(res => {
console.log('opMap', res)
ws.init(token, res.data)
})
.catch(err => {
console.log('err', err)
})
} }
return ( return (
<View className='login'> <View className='login'>

23
src/store/conn.js

@ -0,0 +1,23 @@
const connSlice = createSlice({
name: 'conn',
initialState: {
status: 0, // 连接状态,0未连接,1,已连接,2已关闭
ttl: 0, // 延迟ms
},
reducers: {
connected: state => {
state.status = 1;
},
disconnect: state => {
state.status = 2;
},
setTTL: (state, action) => {
state.ttl = action.playload;
}
}
})
export default connSlice
export const { connected, disconnect, setTTL } = connSlice.actions

6
src/store/index.js

@ -1,5 +1,7 @@
import { configureStore, combineReducers, createSlice } from '@reduxjs/toolkit' import { configureStore, combineReducers, createSlice } from '@reduxjs/toolkit'
import connSlice from '@/store/conn'
const counterSlice = createSlice({ const counterSlice = createSlice({
name: 'counter', name: 'counter',
initialState: { value: 0 }, initialState: { value: 0 },
@ -13,9 +15,11 @@ const counterSlice = createSlice({
} }
}) })
// redux-toolkit: https://redux-toolkit.js.org/usage/immer-reducers
const store = configureStore({ const store = configureStore({
reducer: { reducer: {
counter: counterSlice.reducer counter: counterSlice.reducer,
conn: connSlice.reducer,
} }
}) })

Loading…
Cancel
Save