三国卡牌客户端基础资源仓库
dabaoji
20 小时以前 6c455c41966ec884fada1ffce7389461b11723b6
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
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
 
var LibraryWebSocket = {
    $webSocketState: {
        /*
         * Map of instances
         *
         * Instance structure:
         * {
         *     url: string,
         *     ws: WebSocket
         * }
         */
        instances: {},
 
        /* Last instance ID */
        lastId: 0,
 
        /* Event listeners */
        onOpen: null,
        onMessage: null,
        onError: null,
        onClose: null,
 
        /* Debug mode */
        debug: false
    },
 
    /**
     * Set onOpen callback
     *
     * @param callback Reference to C# static function
     */
    WebSocketSetOnOpen: function(callback) {
 
        webSocketState.onOpen = callback;
 
    },
 
    /**
     * Set onMessage callback
     *
     * @param callback Reference to C# static function
     */
    WebSocketSetOnMessage: function(callback) {
 
        webSocketState.onMessage = callback;
 
    },
 
    /**
     * Set onError callback
     *
     * @param callback Reference to C# static function
     */
    WebSocketSetOnError: function(callback) {
 
        webSocketState.onError = callback;
 
    },
 
    /**
     * Set onClose callback
     *
     * @param callback Reference to C# static function
     */
    WebSocketSetOnClose: function(callback) {
 
        webSocketState.onClose = callback;
 
    },
 
    /**
     * Allocate new WebSocket instance struct
     *
     * @param url Server URL
     */
    WebSocketAllocate: function(url) {
 
        var urlStr = UTF8ToString(url);
        var id = webSocketState.lastId++;
 
        webSocketState.instances[id] = {
          subprotocols: [],
            url: urlStr,
            ws: null
        };
 
        return id;
 
    },
 
  /**
   * Add subprotocol to instance
   *
   * @param instanceId Instance ID
   * @param subprotocol Subprotocol name to add to instance
   */
  WebSocketAddSubProtocol: function(instanceId, subprotocol) {
 
    var subprotocolStr = UTF8ToString(subprotocol);
    webSocketState.instances[instanceId].subprotocols.push(subprotocolStr);
 
  },
 
    /**
     * Remove reference to WebSocket instance
     *
     * If socket is not closed function will close it but onClose event will not be emitted because
     * this function should be invoked by C# WebSocket destructor.
     *
     * @param instanceId Instance ID
     */
    WebSocketFree: function(instanceId) {
 
        var instance = webSocketState.instances[instanceId];
 
        if (!instance) return 0;
 
        // Close if not closed
        if (instance.ws && instance.ws.readyState < 2)
            instance.ws.close();
 
        // Remove reference
        delete webSocketState.instances[instanceId];
 
        return 0;
 
    },
 
    /**
     * Connect WebSocket to the server
     *
     * @param instanceId Instance ID
     */
    WebSocketConnect: function(instanceId) {
 
        var instance = webSocketState.instances[instanceId];
        if (!instance) return -1;
 
        if (instance.ws !== null)
            return -2;
 
        instance.ws = new WebSocket(instance.url, instance.subprotocols);
 
        instance.ws.binaryType = 'arraybuffer';
 
        instance.ws.onopen = function() {
 
            if (webSocketState.debug)
                console.log("[JSLIB WebSocket] Connected.");
 
            if (webSocketState.onOpen)
                Module.dynCall_vi(webSocketState.onOpen, instanceId);
 
        };
 
        instance.ws.onmessage = function(ev) {
 
            if (webSocketState.debug)
                console.log("[JSLIB WebSocket] Received message:", ev.data);
 
            if (webSocketState.onMessage === null)
                return;
 
            if (ev.data instanceof ArrayBuffer) {
 
                var dataBuffer = new Uint8Array(ev.data);
 
                var buffer = _malloc(dataBuffer.length);
                HEAPU8.set(dataBuffer, buffer);
 
                try {
                    Module.dynCall_viii(webSocketState.onMessage, instanceId, buffer, dataBuffer.length);
                } finally {
                    _free(buffer);
                }
 
      } else {
                var dataBuffer = (new TextEncoder()).encode(ev.data);
 
                var buffer = _malloc(dataBuffer.length);
                HEAPU8.set(dataBuffer, buffer);
 
                try {
                    Module.dynCall_viii(webSocketState.onMessage, instanceId, buffer, dataBuffer.length);
                } finally {
                    _free(buffer);
                }
 
      }
 
        };
 
        instance.ws.onerror = function(ev) {
 
            if (webSocketState.debug)
                console.log("[JSLIB WebSocket] Error occured.");
 
            if (webSocketState.onError) {
 
                var pageProtocol = (typeof window !== 'undefined' && window.location) ? window.location.protocol : 'unknown:';
                var pageHref = (typeof window !== 'undefined' && window.location) ? window.location.href : 'unknown';
                var readyState = instance.ws ? instance.ws.readyState : -1;
                var hints = [];
 
                if (pageProtocol === 'https:' && instance.url.indexOf('ws://') === 0)
                    hints.push('HTTPS 页面不能连接非安全 ws://,需要改为 wss://');
 
                if (readyState === 3)
                    hints.push('连接在握手阶段已关闭,常见原因:目标端口不是 WebSocket 服务、服务端未处理 Upgrade 握手、端口未开放或反向代理未透传 Upgrade 头');
 
                var msg = '[JSLIB WebSocket] error url=' + instance.url +
                    ' pageProtocol=' + pageProtocol +
                    ' readyState=' + readyState +
                    ' hasSubProtocols=' + (instance.subprotocols && instance.subprotocols.length > 0 ? 'true' : 'false') +
                    ' page=' + pageHref;
 
                if (hints.length > 0)
                    msg += ' hints=' + hints.join(' | ');
 
                var length = lengthBytesUTF8(msg) + 1;
                var buffer = _malloc(length);
                stringToUTF8(msg, buffer, length);
 
                try {
                    Module.dynCall_vii(webSocketState.onError, instanceId, buffer);
                } finally {
                    _free(buffer);
                }
 
            }
 
        };
 
        instance.ws.onclose = function(ev) {
 
            if (webSocketState.debug)
                console.log("[JSLIB WebSocket] Closed.");
 
            if (webSocketState.onError && ev.code === 1006) {
                var pageProtocol = (typeof window !== 'undefined' && window.location) ? window.location.protocol : 'unknown:';
                var msg = '[JSLIB WebSocket] abnormal close code=1006 url=' + instance.url +
                    ' pageProtocol=' + pageProtocol +
                    ' reason=' + (ev.reason || '') +
                    ' wasClean=' + (ev.wasClean ? 'true' : 'false') +
                    ' hint=通常表示握手失败或网络层直接拒绝;如果当前端口原本是 TCP 游戏服端口,需要单独提供 WebSocket 网关';
                var length = lengthBytesUTF8(msg) + 1;
                var buffer = _malloc(length);
                stringToUTF8(msg, buffer, length);
 
                try {
                    Module.dynCall_vii(webSocketState.onError, instanceId, buffer);
                } finally {
                    _free(buffer);
                }
            }
 
            if (webSocketState.onClose)
                Module.dynCall_vii(webSocketState.onClose, instanceId, ev.code);
 
            delete instance.ws;
 
        };
 
        return 0;
 
    },
 
    /**
     * Close WebSocket connection
     *
     * @param instanceId Instance ID
     * @param code Close status code
     * @param reasonPtr Pointer to reason string
     */
    WebSocketClose: function(instanceId, code, reasonPtr) {
 
        var instance = webSocketState.instances[instanceId];
        if (!instance) return -1;
 
        if (!instance.ws)
            return -3;
 
        if (instance.ws.readyState === 2)
            return -4;
 
        if (instance.ws.readyState === 3)
            return -5;
 
        var reason = ( reasonPtr ? UTF8ToString(reasonPtr) : undefined );
 
        try {
            instance.ws.close(code, reason);
        } catch(err) {
            return -7;
        }
 
        return 0;
 
    },
 
    /**
     * Send message over WebSocket
     *
     * @param instanceId Instance ID
     * @param bufferPtr Pointer to the message buffer
     * @param length Length of the message in the buffer
     */
    WebSocketSend: function(instanceId, bufferPtr, length) {
 
        var instance = webSocketState.instances[instanceId];
        if (!instance) return -1;
 
        if (!instance.ws)
            return -3;
 
        if (instance.ws.readyState !== 1)
            return -6;
 
        instance.ws.send(HEAPU8.buffer.slice(bufferPtr, bufferPtr + length));
 
        return 0;
 
    },
 
    /**
     * Send text message over WebSocket
     *
     * @param instanceId Instance ID
     * @param bufferPtr Pointer to the message buffer
     * @param length Length of the message in the buffer
     */
    WebSocketSendText: function(instanceId, message) {
 
        var instance = webSocketState.instances[instanceId];
        if (!instance) return -1;
 
        if (!instance.ws)
            return -3;
 
        if (instance.ws.readyState !== 1)
            return -6;
 
        instance.ws.send(UTF8ToString(message));
 
        return 0;
 
    },
 
    /**
     * Return WebSocket readyState
     *
     * @param instanceId Instance ID
     */
    WebSocketGetState: function(instanceId) {
 
        var instance = webSocketState.instances[instanceId];
        if (!instance) return -1;
 
        if (instance.ws)
            return instance.ws.readyState;
        else
            return 3;
 
    }
 
};
 
autoAddDeps(LibraryWebSocket, '$webSocketState');
mergeInto(LibraryManager.library, LibraryWebSocket);