-
Notifications
You must be signed in to change notification settings - Fork 24k
/
WebSocket.ios.js
104 lines (91 loc) · 2.53 KB
/
WebSocket.ios.js
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
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule WebSocket
*
*/
'use strict';
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var RCTWebSocketManager = require('NativeModules').WebSocketManager;
var WebSocketBase = require('WebSocketBase');
var WebSocketId = 0;
class WebSocket extends WebSocketBase {
_socketId: number;
_subs: any;
connectToSocketImpl(url: string): void {
this._socketId = WebSocketId++;
RCTWebSocketManager.connect(url, this._socketId);
this._registerEvents(this._socketId);
}
closeConnectionImpl(): void {
RCTWebSocketManager.close(this._socketId);
}
cancelConnectionImpl(): void {
RCTWebSocketManager.close(this._socketId);
}
sendStringImpl(message: string): void {
RCTWebSocketManager.send(message, this._socketId);
}
sendArrayBufferImpl(): void {
// TODO
console.warn('Sending ArrayBuffers is not yet supported');
}
_unregisterEvents(): void {
this._subs.forEach(e => e.remove());
this._subs = [];
}
_registerEvents(id: number): void {
this._subs = [
RCTDeviceEventEmitter.addListener(
'websocketMessage',
function(ev) {
if (ev.id !== id) {
return;
}
this.onmessage && this.onmessage({
data: ev.data
});
}.bind(this)
),
RCTDeviceEventEmitter.addListener(
'websocketOpen',
function(ev) {
if (ev.id !== id) {
return;
}
this.readyState = this.OPEN;
this.onopen && this.onopen();
}.bind(this)
),
RCTDeviceEventEmitter.addListener(
'websocketClosed',
function(ev) {
if (ev.id !== id) {
return;
}
this.readyState = this.CLOSED;
this.onclose && this.onclose(ev);
this._unregisterEvents();
RCTWebSocketManager.close(id);
}.bind(this)
),
RCTDeviceEventEmitter.addListener(
'websocketFailed',
function(ev) {
if (ev.id !== id) {
return;
}
this.onerror && this.onerror(new Error(ev.message));
this._unregisterEvents();
RCTWebSocketManager.close(id);
}.bind(this)
)
];
}
}
module.exports = WebSocket;