messageSocket.js
6.07 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/**
* 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.
*/
'use strict';
const url = require('url');
const WebSocketServer = require('ws').Server;
const PROTOCOL_VERSION = 2;
const notifier = require('node-notifier');
function parseMessage(data, binary) {
if (binary) {
console.error('Expected text message, got binary!');
return undefined;
}
try {
const message = JSON.parse(data);
if (message.version === PROTOCOL_VERSION) {
return message;
}
console.error('Received message had wrong protocol version: '
+ message.version);
} catch (e) {
console.error('Failed to parse the message as JSON:\n' + data);
}
return undefined;
}
function isBroadcast(message) {
return (
typeof message.method === 'string' &&
message.id === undefined &&
message.target === undefined
);
}
function isRequest(message) {
return (
typeof message.method === 'string' &&
typeof message.target === 'string');
}
function isResponse(message) {
return (
typeof message.id === 'object' &&
typeof message.id.requestId !== undefined &&
typeof message.id.clientId === 'string' && (
message.result !== undefined ||
message.error !== undefined
));
}
function attachToServer(server, path) {
const wss = new WebSocketServer({
server: server,
path: path
});
const clients = new Map();
let nextClientId = 0;
function getClientWs(clientId) {
const clientWs = clients.get(clientId);
if (clientWs === undefined) {
throw `could not find id "${clientId}" while forwarding request`;
}
return clientWs;
}
function handleSendBroadcast(broadcasterId, message) {
const forwarded = {
version: PROTOCOL_VERSION,
method: message.method,
params: message.params,
};
if (clients.size === 0) {
notifier.notify({
'title': 'React Native: No apps connected',
'message': `Sending '${message.method}' to all React Native apps ` +
'failed. Make sure your app is running in the simulator ' +
'or on a phone connected via USB.'
});
}
for (const [otherId, otherWs] of clients) {
if (otherId !== broadcasterId) {
try {
otherWs.send(JSON.stringify(forwarded));
} catch (e) {
console.error(`Failed to send broadcast to client: '${otherId}' ` +
`due to:\n ${e.toString()}`);
}
}
}
}
wss.on('connection', function(clientWs) {
const clientId = `client#${nextClientId++}`;
function handleCaughtError(message, error) {
const errorMessage = {
id: message.id,
method: message.method,
target: message.target,
error: message.error === undefined ? 'undefined' : 'defined',
params: message.params === undefined ? 'undefined' : 'defined',
result: message.result === undefined ? 'undefined' : 'defined',
};
if (message.id === undefined) {
console.error(
`Handling message from ${clientId} failed with:\n${error}\n` +
`message:\n${JSON.stringify(errorMessage)}`);
} else {
try {
clientWs.send(JSON.stringify({
version: PROTOCOL_VERSION,
error: error,
id: message.id,
}));
} catch (e) {
console.error(`Failed to reply to ${clientId} with error:\n${error}` +
`\nmessage:\n${JSON.stringify(errorMessage)}` +
`\ndue to error: ${e.toString()}`);
}
}
}
function handleServerRequest(message) {
let result = null;
switch (message.method) {
case 'getid':
result = clientId;
break;
case 'getpeers':
result = {};
clients.forEach((otherWs, otherId) => {
if (clientId !== otherId) {
result[otherId] = url.parse(otherWs.upgradeReq.url, true).query;
}
});
break;
default:
throw `unknown method: ${message.method}`;
}
clientWs.send(JSON.stringify({
version: PROTOCOL_VERSION,
result: result,
id: message.id
}));
}
function forwardRequest(message) {
getClientWs(message.target).send(JSON.stringify({
version: PROTOCOL_VERSION,
method: message.method,
params: message.params,
id: (message.id === undefined
? undefined
: {requestId: message.id, clientId: clientId}),
}));
}
function forwardResponse(message) {
getClientWs(message.id.clientId).send(JSON.stringify({
version: PROTOCOL_VERSION,
result: message.result,
error: message.error,
id: message.id.requestId,
}));
}
clients.set(clientId, clientWs);
clientWs.onclose =
clientWs.onerror = () => {
clientWs.onmessage = null;
clients.delete(clientId);
};
clientWs.onmessage = (event) => {
const message = parseMessage(event.data, event.binary);
if (message === undefined) {
console.error('Received message not matching protocol');
return;
}
try {
if (isBroadcast(message)) {
handleSendBroadcast(clientId, message);
} else if (isRequest(message)) {
if (message.target === 'server') {
handleServerRequest(message);
} else {
forwardRequest(message);
}
} else if (isResponse(message)) {
forwardResponse(message);
} else {
throw 'Invalid message, did not match the protocol';
}
} catch (e) {
handleCaughtError(message, e.toString());
}
};
});
return {
broadcast: (method, params) => {
handleSendBroadcast(null, {method: method, params: params});
}
};
}
module.exports = {
attachToServer: attachToServer,
parseMessage: parseMessage,
};