index.uts 8.4 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
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
import webSocket from '@ohos.net.webSocket';
import {
    ConnectSocket,
    ConnectSocketOptions,
    SocketTask as UniSocketTask,
    SendSocketMessageOptions,
    CloseSocketOptions,
    GeneralCallbackResult,
    OnSocketMessageCallbackResult,
    ConnectSocketSuccess,
    OnSocketErrorCallbackResult,
    CloseSocket,
    SendSocketMessage,
    OnSocketMessage,
    OnSocketOpen,
    OnSocketClose,
    OnSocketError,
} from '../interface.uts'
import {
    API_CONNECT_SOCKET,
    ConnectSocketApiProtocol,
    ConnectSocketApiOptions,
    API_SEND_SOCKET_MESSAGE,
    API_CLOSE_SOCKET,
} from '../protocol.uts'
import {
DCloud-yyl's avatar
DCloud-yyl 已提交
27 28
    Emitter,
    getCurrentMP,
DCloud-yyl's avatar
DCloud-yyl 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41
} from '@dcloudio/uni-runtime'

export {
    ConnectSocket,
    ConnectSocketOptions,
    UniSocketTask as SocketTask,
    SendSocketMessageOptions,
    CloseSocketOptions,
    OnSocketMessageCallbackResult,
    ConnectSocketSuccess,
    OnSocketErrorCallbackResult
}

DCloud-yyl's avatar
DCloud-yyl 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54
interface UniWebsocketMP {
    id: string
    on: Function
    off: Function
}

interface IUniWebsocketEmitter {
    on: (eventName: string, callback: Function) => void
    once: (eventName: string, callback: Function) => void
    off: (eventName: string, callback?: Function | null) => void
    emit: (eventName: string, ...args: (Object | undefined | null)[]) => void
}

DCloud-yyl's avatar
DCloud-yyl 已提交
55 56 57 58 59 60 61 62 63 64 65
function tryExec(fn: Function | null | undefined, ...args: any[]) {
    if (!fn) {
        return
    }
    try {
        fn(...args)
    } catch (error) {
        console.error(error)
    }
}

DCloud-yyl's avatar
DCloud-yyl 已提交
66
const GlobalWebsocketEmitter = new Emitter() as IUniWebsocketEmitter
DCloud-yyl's avatar
DCloud-yyl 已提交
67

DCloud-yyl's avatar
DCloud-yyl 已提交
68 69 70 71 72 73
function destroySocketTaskEmitter(emitter: IUniWebsocketEmitter) {
    emitter.off('message')
    emitter.off('open')
    emitter.off('error')
    emitter.off('close')
}
DCloud-yyl's avatar
DCloud-yyl 已提交
74 75

class SocketTask implements UniSocketTask {
DCloud-yyl's avatar
DCloud-yyl 已提交
76
    _destroy: Function
DCloud-yyl's avatar
DCloud-yyl 已提交
77
    private _ws: webSocket.WebSocket;
DCloud-yyl's avatar
DCloud-yyl 已提交
78
    private _emitter: IUniWebsocketEmitter = new Emitter() as IUniWebsocketEmitter
DCloud-yyl's avatar
DCloud-yyl 已提交
79
    constructor(ws: webSocket.WebSocket) {
DCloud-yyl's avatar
DCloud-yyl 已提交
80
        const mp = getCurrentMP() as UniWebsocketMP
DCloud-yyl's avatar
DCloud-yyl 已提交
81 82 83 84 85 86
        this._ws = ws;
        this._ws.on('message', (_, data) => {
            const message = {
                data
            } as OnSocketMessageCallbackResult
            this._emitter.emit('message', message)
DCloud-yyl's avatar
DCloud-yyl 已提交
87
            const socketTasks = getSocketTasks(mp.id)
DCloud-yyl's avatar
DCloud-yyl 已提交
88
            if (this === socketTasks[0]) {
DCloud-yyl's avatar
DCloud-yyl 已提交
89
                GlobalWebsocketEmitter.emit('message', message)
DCloud-yyl's avatar
DCloud-yyl 已提交
90 91 92 93
            }
        })
        this._ws.on('open', (_, data) => {
            this._emitter.emit('open', data)
DCloud-yyl's avatar
DCloud-yyl 已提交
94
            const socketTasks = getSocketTasks(mp.id)
DCloud-yyl's avatar
DCloud-yyl 已提交
95
            if (this === socketTasks[0]) {
DCloud-yyl's avatar
DCloud-yyl 已提交
96
                GlobalWebsocketEmitter.emit('open', data)
DCloud-yyl's avatar
DCloud-yyl 已提交
97 98 99 100 101 102 103
            }
        })
        this._ws.on('error', (error) => {
            const message = {
                errMsg: error.message
            } as OnSocketErrorCallbackResult
            this._emitter.emit('error', message)
DCloud-yyl's avatar
DCloud-yyl 已提交
104
            const socketTasks = getSocketTasks(mp.id)
DCloud-yyl's avatar
DCloud-yyl 已提交
105
            if (this === socketTasks[0]) {
DCloud-yyl's avatar
DCloud-yyl 已提交
106
                GlobalWebsocketEmitter.emit('error', message)
DCloud-yyl's avatar
DCloud-yyl 已提交
107 108 109 110
            }
        })
        this._ws.on('close', (_, data) => {
            this._emitter.emit('close', data)
DCloud-yyl's avatar
DCloud-yyl 已提交
111
            const socketTasks = getSocketTasks(mp.id)
DCloud-yyl's avatar
DCloud-yyl 已提交
112
            if (this === socketTasks[0]) {
DCloud-yyl's avatar
DCloud-yyl 已提交
113
                GlobalWebsocketEmitter.emit('close', data)
DCloud-yyl's avatar
DCloud-yyl 已提交
114 115 116 117 118 119
            }
            const index = socketTasks.indexOf(this)
            if (index >= 0) {
                socketTasks.splice(index, 1)
            }
        })
DCloud-yyl's avatar
DCloud-yyl 已提交
120 121 122 123
        this._destroy = () => {
            destroySocketTaskEmitter(this._emitter)
            this.close()
        }
DCloud-yyl's avatar
DCloud-yyl 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    }

    send(options: SendSocketMessageOptions) {
        this._ws.send(options.data as string | ArrayBuffer).then((success: boolean) => {
            if (success) {
                tryExec(options.success, {} as GeneralCallbackResult)
            } else {
                tryExec(options.fail, new UniError('send message failed'))
            }
        }, (err: Error) => {
            tryExec(options.fail, new UniError(err.message))
        })
    }

    close(options?: CloseSocketOptions) {
        this._ws.close({
            code: typeof options?.code === 'number' ? options.code : 1000,
            reason: typeof options?.reason === 'string' ? options.reason : '',
        } as webSocket.WebSocketCloseOptions).then((success: boolean) => {
            if (success) {
                tryExec(options?.success, {} as GeneralCallbackResult)
            } else {
                tryExec(options?.fail, new UniError('close socket failed'))
            }
        }, (err: Error) => {
            tryExec(options?.fail, new UniError(err.message))
        })
    }

    onMessage(callback: Function) {
        this._emitter.on('message', callback)
    }

    onOpen(callback: Function) {
        this._emitter.on('open', callback)
    }

    onError(callback: Function) {
        this._emitter.on('error', callback)
    }

    onClose(callback: Function) {
        this._emitter.on('close', callback)
    }
}

DCloud-yyl's avatar
DCloud-yyl 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
const socketTasksMap: Map<string, SocketTask[]> = new Map()

function addSocketTask(task: SocketTask) {
    const mp = getCurrentMP() as UniWebsocketMP
    mp.on('beforeClose', task._destroy)
    task.onClose(() => {
        mp.off('beforeClose', task._destroy)
    })
    const id = mp.id
    if (!socketTasksMap.has(id)) {
        socketTasksMap.set(id, [])
    }
    const socketTasks = socketTasksMap.get(id) as SocketTask[]
    socketTasks.push(task)
}

function getSocketTasks(id?: string) {
    if (!id) {
        const mp = getCurrentMP() as UniWebsocketMP
        id = mp.id
    }
    return socketTasksMap.get(id) || []
}
DCloud-yyl's avatar
DCloud-yyl 已提交
193 194 195 196 197

export const connectSocket = defineTaskApi<ConnectSocketOptions, ConnectSocketSuccess, UniSocketTask>(
    API_CONNECT_SOCKET,
    function (args: ConnectSocketOptions, exec: ApiExecutor<ConnectSocketSuccess>) {
        const ws = webSocket.createWebSocket();
DCloud-yyl's avatar
DCloud-yyl 已提交
198
        const mp = getCurrentMP() as UniWebsocketMP
DCloud-yyl's avatar
DCloud-yyl 已提交
199 200 201 202 203 204
        ws.connect(args.url, {
            header: args.header ? args.header as Object : undefined,
            protocol: args.protocols ?
                Array.isArray(args.protocols) ?
                    args.protocols.join(',') :
                    args.protocols :
DCloud-yyl's avatar
DCloud-yyl 已提交
205
                '',
DCloud-yyl's avatar
DCloud-yyl 已提交
206 207
        } as webSocket.WebSocketRequestOptions);
        const task = new SocketTask(ws);
DCloud-yyl's avatar
DCloud-yyl 已提交
208 209 210 211 212
        mp.on('beforeClose', task._destroy)
        task.onClose(() => {
            mp.off('beforeClose', task._destroy)
        })
        addSocketTask(task)
DCloud-yyl's avatar
DCloud-yyl 已提交
213 214 215 216 217 218 219
        return task
    },
    ConnectSocketApiProtocol,
    ConnectSocketApiOptions
) as ConnectSocket

export const onSocketMessage: OnSocketMessage = function (callback: Function) {
DCloud-yyl's avatar
DCloud-yyl 已提交
220
    GlobalWebsocketEmitter.on('message', callback)
DCloud-yyl's avatar
DCloud-yyl 已提交
221 222 223
}

export const onSocketOpen: OnSocketOpen = function (callback: Function) {
DCloud-yyl's avatar
DCloud-yyl 已提交
224
    GlobalWebsocketEmitter.on('open', callback)
DCloud-yyl's avatar
DCloud-yyl 已提交
225 226 227
}

export const onSocketError: OnSocketError = function (callback: Function) {
DCloud-yyl's avatar
DCloud-yyl 已提交
228
    GlobalWebsocketEmitter.on('error', callback)
DCloud-yyl's avatar
DCloud-yyl 已提交
229 230 231
}

export const onSocketClose: OnSocketClose = function (callback: Function) {
DCloud-yyl's avatar
DCloud-yyl 已提交
232
    GlobalWebsocketEmitter.on('close', callback)
DCloud-yyl's avatar
DCloud-yyl 已提交
233 234 235 236 237
}

export const sendSocketMessage = defineAsyncApi<SendSocketMessageOptions, GeneralCallbackResult>(
    API_SEND_SOCKET_MESSAGE,
    function (args: SendSocketMessageOptions, exec: ApiExecutor<GeneralCallbackResult>) {
DCloud-yyl's avatar
DCloud-yyl 已提交
238
        const socketTasks = getSocketTasks()
DCloud-yyl's avatar
DCloud-yyl 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
        const task = socketTasks[0]
        if (task) {
            task.send({
                data: args.data,
                success(res) {
                    exec.resolve(res)
                },
                fail(err) {
                    exec.reject('sendSocketMessage:fail')
                },
            } as SendSocketMessageOptions)
        } else {
            exec.reject('WebSocket is not connected')
        }
    }
) as SendSocketMessage

export const closeSocket = defineAsyncApi<CloseSocketOptions, GeneralCallbackResult>(
    API_CLOSE_SOCKET,
    function (args: CloseSocketOptions, exec: ApiExecutor<GeneralCallbackResult>) {
DCloud-yyl's avatar
DCloud-yyl 已提交
259
        const socketTasks = getSocketTasks()
DCloud-yyl's avatar
DCloud-yyl 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        const task = socketTasks[0]
        if (task) {
            task.close({
                code: args.code,
                reason: args.reason,
                success(res) {
                    exec.resolve(res)
                },
                fail(err) {
                    exec.reject('closeSocket:fail')
                },
            } as CloseSocketOptions)
        } else {
            exec.reject('WebSocket is not connected')
        }
    }
) as CloseSocket