-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathWebSocketApi.js
More file actions
199 lines (170 loc) · 6.74 KB
/
Copy pathWebSocketApi.js
File metadata and controls
199 lines (170 loc) · 6.74 KB
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
class WebSocket {
static CONNECTING = 0
static OPEN = 1
static CLOSING = 2
static CLOSED = 3
#url;
//#readyState;
webSocketId;
onmessage = null;
onopen = null;
onerror = null;
onclose = null;
constructor(url, protocols) {
//TODO: add checks if Scene can actually use WebSocket
this.webSocketId = UnityWebSocketApi.Create(url);
this.#url = url;
this.#connect().then(() => {
this.#receive().catch(error => {
console.error('Error receiving data:', error);
});
}).catch(error => {
console.error('Error connecting:', error);
});
// console.log("WS: ", `${url} contructor has finished`);
}
#connect() {
//this.#readyState = WebSocket.CONNECTING;
return UnityWebSocketApi.ConnectAsync(this.webSocketId, this.#url).then(() => {
// this.#readyState = WebSocket.OPEN
if (typeof this.onopen === 'function') {
this.onopen({type: "open"});
}
}).catch(error => {
if (typeof this.onerror === 'function') {
this.onerror(error);
}
});
}
send(data) {
const thisReadyState = this.readyState;
// console.log("WebSocket.send is called", data.constructor.name, `State is ${thisReadyState}`);
// Per the WHATWG WebSocket spec, send() on a CLOSING/CLOSED socket must NOT throw — the data is
// silently discarded. Throwing on CLOSED bubbled out of the scene update loop and was reported to
// Sentry once per tick by misbehaving scenes (UNITY-EXPLORER-NQE: "WebSocket state is 3, cannot
// send data"). Only a still-CONNECTING socket remains an error.
if (thisReadyState === WebSocket.CLOSING || thisReadyState === WebSocket.CLOSED) {
return;
}
if (thisReadyState !== WebSocket.OPEN) {
const errorMessage = `WebSocket state is ${thisReadyState}, cannot send data`;
throw new Error(errorMessage);
}
let sendPromise;
if (typeof data === 'string') {
sendPromise = UnityWebSocketApi.SendAsync(this.webSocketId, data);
} else if (data instanceof Uint8Array || data instanceof ArrayBuffer || Array.isArray(data)) {
// console.log("WS: WebSocket.send binary is called", data.constructor.name, `length is ${data.length}`);
sendPromise = UnityWebSocketApi.SendAsync(this.webSocketId, data);
} else {
console.error(`Unsupported data type: ${typeof data}`, data);
throw new new Error("Unsupported data type");
}
sendPromise.catch(error => {
if (typeof this.onerror === 'function') {
this.onerror(error);
}
});
}
#receive() {
const self = this;
return new Promise((resolve, reject) => {
const receiveData = () => {
let thisReadyState = self.readyState;
if (thisReadyState === WebSocket.CLOSED || thisReadyState === WebSocket.CLOSING) {
// console.log("WS: Connection is closing or closed. Stopping receive loop.");
resolve();
return;
}
UnityWebSocketApi.ReceiveAsync(self.webSocketId).then(data => {
let messageType;
let body;
switch (data.type) {
case 'Text':
messageType = "text";
body = data.text;
break;
case 'Binary':
messageType = "binary";
body = data.binary;
break;
case 'Close':
// this close is initiated by the server
if (typeof self.onclose === 'function') {
self.onclose({type: "close"});
}
// break the loop
return;
default:
const error = `Unsupported message type ${data.type}. Receive Loop stopped`;
if (typeof self.onerror === 'function') {
self.onerror(error);
}
reject(error);
return;
}
if (typeof self.onmessage === 'function') {
self.onmessage({type: messageType, data: body});
}
// Restart Receive iteration
receiveData();
}).catch(error => {
if (typeof self.onerror === 'function') {
self.onerror(error);
}
reject(error);
});
};
// Start first Receive iteration
receiveData();
});
}
close(code = undefined, reason = undefined) {
const thisReadyState = this.readyState;
if (thisReadyState === WebSocket.OPEN || thisReadyState === WebSocket.CONNECTING) {
//this.#readyState = WebSocket.CLOSING;
UnityWebSocketApi.CloseAsync(this.webSocketId)
.then(() => {
// console.log("WebSocket connection closed");
//this.#readyState = WebSocket.CLOSED;
// this close in initiated by the client
if (typeof this.onclose === 'function') {
this.onclose({type: "close"});
}
})
.catch(error => {
console.error("Error closing WebSocket connection:", error);
});
} else {
const errorMessage = `WebSocket state is ${thisReadyState}, cannot close`;
console.error(errorMessage);
throw new Error(errorMessage);
}
}
get readyState() {
// can't store the state in JS as it can be modified from the managed side without any notification
return UnityWebSocketApi.GetState(this.webSocketId);
}
get binaryType() {
return "arraybuffer"
}
set binaryType(value) {
if (value !== "arraybuffer") {
throw new Error("Only 'arraybuffer' is supported as binaryType")
}
}
get protocol() {
return ""
}
get extensions() {
return ""
}
// There is no send buffer here, it is handled on C# side
get bufferedAmount() {
return 0
}
get url() {
return this.#url;
}
}
module.exports.WebSocket = WebSocket