likes
comments
collection
share

一个基于json的快速建立websocket解决方案,支持node、web,可以自定义middlew

作者站长头像
站长
· 阅读数 43

前端快速建立和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
  }
}

转载自:https://segmentfault.com/a/1190000041261119
评论
请登录