前端疾速建设和 node 建设 websocket,应用 json 格局,反对中间件。示例如下,前后端疾速传递服务器工夫戳。联合 redux 几行代码即可将数据传递到 react 组件。
github: https://github.com/stillyuk/j…
server
let websocketServer = new JsonWebsocketServer(8899)
websocketServer.start()
websocketServer.addTask(new ServerTimestampTask(websocketServer))
websocketServer.use(middleware.ip)
websocketServer.use(middleware.version)
websocketServer.use(async (connInfo, clientData, next) => {if (clientData.token !== 'abc') {websocketServer.sendClient([connInfo], 'error', {errorCode: 1, errorMsg: 'login first'})
} else {await next()
}
})
client
import JsonWebsocketClient from '../src/JsonWebsocketClient.js'
let client = new JsonWebsocketClient('ws:localhost:8899')
client.addWatch('serverTimestamp', null, (a) => {console.log(a)
})
client.addWatch('version', '1.0')
client.addWatch('error', null, (data) => {console.log(data)
})
redux middleware and reducer
//middleware
const webSocketClient = new JsonWebsocketClient()
export function wsUpdateType(type) {return type + '_ws_update'}
export default () => next => async (action: any) => {if (!action.wsType) {return next(action)
}
if (action.wsType == 'close') {webSocketClient.close(action.data)
return
}
webSocketClient.addWatch(action.wsType, action.data, (data) => {
return next({type: wsUpdateType(action.type),
data: data
})
})
}
//reducer
function socket(type, value) {return (state = value, action) => {if (action.type == wsUpdateType(type)) {return action.data}
return state
}
}