socket.ts 7.3 KB
Newer Older
D
DCloud_LXH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
import {
  defineTaskApi,
  defineAsyncApi,
  defineOnApi,
  API_CONNECT_SOCKET,
  API_TYPE_CONNECT_SOCKET,
  ConnectSocketProtocol,
  ConnectSocketOptions,
  API_SEND_SOCKET_MESSAGE,
  API_TYPE_SEND_SOCKET_MESSAGE,
  SendSocketMessageProtocol,
  API_CLOSE_SOCKET,
  API_TYPE_CLOSE_SOCKET,
  CloseSocketProtocol,
} from '@dcloudio/uni-api'
import { requireNativePlugin } from '../base'
import { base64ToArrayBuffer, arrayBufferToBase64 } from '@dcloudio/uni-api'
import { extend, capitalize } from '@vue/shared'
import { callOptions } from '@dcloudio/uni-shared'

type Socket = {
D
DCloud_LXH 已提交
22 23 24 25 26 27 28 29 30 31 32
  send: ({
    data,
  }: {
    id: String
    data:
      | string
      | {
          '@type': String
          base64: String
        }
  }) => void
D
DCloud_LXH 已提交
33
  close: ({ code, reason }: { code?: number; reason?: string }) => void
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
  onopen: (cb: (args: { id: string }) => void) => void
  onmessage: (
    cb: (args: { id: string; message: string | Object }) => void
  ) => void
  onerror: (cb: (args: { id: string; message: string }) => void) => void
  onclose: (
    cb: (args: {
      id: string
      code: number
      reason: string
      wasClean: boolean
    }) => void
  ) => void
  WebSocket: (args: {
    id: string
    url: string
    protocol?: string
    header?: any
  }) => void
D
DCloud_LXH 已提交
53 54 55
}
type eventName = keyof WebSocketEventMap
const socketTasks: SocketTask[] = []
56
const socketsMap: Record<string, SocketTask> = {}
D
DCloud_LXH 已提交
57 58 59 60 61 62 63 64
const globalEvent: Record<eventName, string> = {
  open: '',
  close: '',
  error: '',
  message: '',
}

let socket: Socket
65
function createSocketTask(args: UniApp.ConnectSocketOption) {
D
DCloud_LXH 已提交
66 67 68 69 70
  const socketId = String(Date.now())
  let errMsg
  try {
    if (!socket) {
      socket = requireNativePlugin('uni-webSocket')
71
      bindSocketCallBack(socket)
D
DCloud_LXH 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    }
    socket.WebSocket({
      id: socketId,
      url: args.url,
      protocol: Array.isArray(args.protocols)
        ? args.protocols.join(',')
        : args.protocols,
      header: args.header,
    })
  } catch (error) {
    errMsg = error
  }
  return { socket, socketId, errMsg }
}

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
function bindSocketCallBack(socket: Socket) {
  socket.onopen((e) => {
    const curSocket = socketsMap[e.id]
    if (!curSocket) return
    curSocket._socketOnOpen()
  })
  socket.onmessage((e) => {
    const curSocket = socketsMap[e.id]
    if (!curSocket) return
    curSocket._socketOnMessage(e)
  })
  socket.onerror((e) => {
    const curSocket = socketsMap[e.id]
    if (!curSocket) return
    curSocket._socketOnError()
  })
  socket.onclose((e) => {
    const curSocket = socketsMap[e.id]
    if (!curSocket) return
    curSocket._socketOnClose()
  })
}

D
DCloud_LXH 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
class SocketTask implements UniApp.SocketTask {
  private _callbacks: {
    open: Function[]
    close: Function[]
    error: Function[]
    message: Function[]
  }
  _socket: Socket
  id: string
  CLOSED: number
  CLOSING: number
  CONNECTING: number
  OPEN: number
  readyState: number
  constructor(socket: Socket, socketId: string) {
    this.id = socketId
    this._socket = socket
    this._callbacks = {
      open: [],
      close: [],
      error: [],
      message: [],
    }
    this.CLOSED = 3
    this.CLOSING = 2
    this.CONNECTING = 0
    this.OPEN = 1
    this.readyState = this.CLOSED

    if (!this._socket) return
140
  }
D
DCloud_LXH 已提交
141

142 143 144 145 146 147 148 149 150 151 152
  _socketOnOpen() {
    this.readyState = this.OPEN
    this.socketStateChange('open')
  }

  _socketOnMessage(e: any) {
    this.socketStateChange('message', {
      data:
        typeof e.data === 'object'
          ? base64ToArrayBuffer(e.data.base64)
          : e.data,
D
DCloud_LXH 已提交
153 154 155
    })
  }

156 157 158 159 160 161 162 163 164 165
  _socketOnError() {
    this.socketStateChange('error')
    this.onErrorOrClose()
  }

  _socketOnClose() {
    this.socketStateChange('close')
    this.onErrorOrClose()
  }

D
DCloud_LXH 已提交
166 167
  onErrorOrClose() {
    this.readyState = this.CLOSED
168
    delete socketsMap[this.id]
D
DCloud_LXH 已提交
169 170 171 172 173 174 175
    const index = socketTasks.indexOf(this)
    if (index >= 0) {
      socketTasks.splice(index, 1)
    }
  }

  socketStateChange(name: eventName, res: Data = {}) {
176 177
    const data = name === 'message' ? res : {}

D
DCloud_LXH 已提交
178
    if (this === socketTasks[0] && globalEvent[name]) {
179
      UniServiceJSBridge.invokeOnCallback(globalEvent[name], data)
D
DCloud_LXH 已提交
180 181 182 183 184
    }

    // WYQ fix: App平台修复websocket onOpen时发送数据报错的Bug
    this._callbacks[name].forEach((callback) => {
      if (typeof callback === 'function') {
185
        callback(data)
D
DCloud_LXH 已提交
186 187 188 189
      }
    })
  }

D
DCloud_LXH 已提交
190
  send(args: UniApp.SendSocketMessageOptions, callopt: boolean = true) {
D
DCloud_LXH 已提交
191 192 193 194 195
    if (this.readyState !== this.OPEN) {
      callOptions(args, 'sendSocketMessage:fail WebSocket is not connected')
    }
    try {
      this._socket.send({
D
DCloud_LXH 已提交
196 197 198 199 200 201 202 203
        id: this.id,
        data:
          typeof args.data === 'object'
            ? {
                '@type': 'binary',
                base64: arrayBufferToBase64(args.data),
              }
            : args.data,
D
DCloud_LXH 已提交
204
      })
D
DCloud_LXH 已提交
205
      callopt && callOptions(args, 'sendSocketMessage:ok')
D
DCloud_LXH 已提交
206
    } catch (error) {
D
DCloud_LXH 已提交
207
      callopt && callOptions(args, `sendSocketMessage:fail ${error}`)
D
DCloud_LXH 已提交
208 209 210
    }
  }

D
DCloud_LXH 已提交
211
  close(args: UniApp.CloseSocketOptions, callopt: boolean = true) {
D
DCloud_LXH 已提交
212 213
    this.readyState = this.CLOSING
    try {
D
DCloud_LXH 已提交
214 215 216 217 218 219
      this._socket.close(
        extend({
          id: this.id,
          args,
        })
      )
D
DCloud_LXH 已提交
220
      callopt && callOptions(args!, 'closeSocket:ok')
D
DCloud_LXH 已提交
221
    } catch (error) {
D
DCloud_LXH 已提交
222
      callopt && callOptions(args!, `closeSocket:fail ${error}`)
D
DCloud_LXH 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    }
  }

  onOpen(callback: Function) {
    this._callbacks.open.push(callback)
  }

  onClose(callback: Function) {
    this._callbacks.close.push(callback)
  }

  onError(callback: Function) {
    this._callbacks.error.push(callback)
  }

  onMessage(callback: Function) {
    this._callbacks.message.push(callback)
  }
}

export const connectSocket = defineTaskApi<API_TYPE_CONNECT_SOCKET>(
  API_CONNECT_SOCKET,
  ({ url, protocols, header, method }, { resolve, reject }) => {
    const { socket, socketId, errMsg } = createSocketTask({
      url,
      protocols,
      header,
      method,
    })
    const socketTask = new SocketTask(socket, socketId)
    if (errMsg) {
      setTimeout(() => {
        reject(errMsg)
      }, 0)
    } else {
      socketTasks.push(socketTask)
259
      socketsMap[socketId] = socketTask
D
DCloud_LXH 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    }
    setTimeout(() => {
      resolve()
    }, 0)
    return socketTask
  },
  ConnectSocketProtocol,
  ConnectSocketOptions
)

export const sendSocketMessage = defineAsyncApi<API_TYPE_SEND_SOCKET_MESSAGE>(
  API_SEND_SOCKET_MESSAGE,
  (args, { resolve, reject }) => {
    const socketTask = socketTasks[0]
    if (!socketTask || socketTask.readyState !== socketTask.OPEN) {
D
DCloud_LXH 已提交
275
      reject('WebSocket is not connected')
D
DCloud_LXH 已提交
276 277
      return
    }
D
DCloud_LXH 已提交
278
    socketTask.send({ data: args.data }, false)
D
DCloud_LXH 已提交
279 280 281 282 283 284 285
    resolve()
  },
  SendSocketMessageProtocol
)

export const closeSocket = defineAsyncApi<API_TYPE_CLOSE_SOCKET>(
  API_CLOSE_SOCKET,
286
  (args, { resolve, reject }) => {
D
DCloud_LXH 已提交
287 288
    const socketTask = socketTasks[0]
    if (!socketTask) {
D
DCloud_LXH 已提交
289
      reject('WebSocket is not connected')
D
DCloud_LXH 已提交
290 291 292
      return
    }
    socketTask.readyState = socketTask.CLOSING
D
DCloud_LXH 已提交
293
    socketTask.close(args, false)
D
DCloud_LXH 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    resolve()
  },
  CloseSocketProtocol
)

function on(event: eventName) {
  const api = `onSocket${capitalize(event)}`
  return defineOnApi(api, () => {
    globalEvent[event] = api
  })
}

export const onSocketOpen = /*#__PURE__*/ on('open')

export const onSocketError = /*#__PURE__*/ on('error')

export const onSocketMessage = /*#__PURE__*/ on('message')

export const onSocketClose = /*#__PURE__*/ on('close')