mh-two-thousand-and-two
2024-04-12 3d2ec2fd0578d3ba0a414b0cc4e4a2ae60878596
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import {
  unpack,
  publish,
  requireNativePlugin,
  base64ToArrayBuffer,
  arrayBufferToBase64
} from '../../bridge'
 
const socketTasks = {}
 
const publishStateChange = (res) => {
  publish('onSocketTaskStateChange', res)
}
 
let socket
function getSocket () {
  if (socket) {
    return socket
  }
  socket = requireNativePlugin('uni-webSocket')
  socket.onopen(function (e) {
    publishStateChange({
      socketTaskId: e.id,
      state: 'open'
    })
  })
  socket.onmessage(function (e) {
    const data = e.data
    publishStateChange({
      socketTaskId: e.id,
      state: 'message',
      data: typeof data === 'object' ? base64ToArrayBuffer(data.base64) : data
    })
  })
  socket.onerror(function (e) {
    publishStateChange({
      socketTaskId: e.id,
      state: 'error',
      errMsg: e.data
    })
  })
  socket.onclose(function (e) {
    const socketTaskId = e.id
    const { code, reason } = e
    delete socketTasks[socketTaskId]
    publishStateChange({
      socketTaskId,
      state: 'close',
      code,
      reason
    })
  })
  return socket
}
 
const createSocketTaskById = function (socketTaskId, {
  url,
  data,
  header,
  method,
  protocols
} = {}) {
  const socket = getSocket()
  socket.WebSocket({
    id: socketTaskId,
    url,
    protocol: Array.isArray(protocols) ? protocols.join(',') : protocols,
    header
  })
  socketTasks[socketTaskId] = socket
  return {
    socketTaskId,
    errMsg: 'createSocketTask:ok'
  }
}
 
export function createSocketTask (args) {
  return createSocketTaskById(String(Date.now()), args)
}
 
export function operateSocketTask (args) {
  const {
    operationType,
    code,
    reason,
    data,
    socketTaskId
  } = unpack(args)
  const socket = socketTasks[socketTaskId]
  if (!socket) {
    return {
      errMsg: 'operateSocketTask:fail'
    }
  }
  switch (operationType) {
    case 'send':
      if (data) {
        socket.send({
          id: socketTaskId,
          data: typeof data === 'object' ? {
            '@type': 'binary',
            base64: arrayBufferToBase64(data)
          } : data
        })
      }
      return {
        errMsg: 'operateSocketTask:ok'
      }
    case 'close':
      socket.close({
        id: socketTaskId,
        code,
        reason
      })
      delete socketTasks[socketTaskId]
      return {
        errMsg: 'operateSocketTask:ok'
      }
  }
  return {
    errMsg: 'operateSocketTask:fail'
  }
}