Skip to content

Commit ebb44d2

Browse files
philikonFacebook Github Bot 0
authored andcommitted
Clean up and simplify WebSocket implementation on the JS side
Summary:- Get rid of no longer necessary WebSocket.js v WebSocketBase.js split - Use `EventTarget(list, of, events)` as base class to auto-generate `oneventname` getters/setters that get invoked along with other event handlers - Type annotation `any` considered harmful, especially when we can easily spell out the actual type - Throw in some `const` goodness for free **Test Plan:** Launch UIExplorer example app, supplied `websocket_test_server` script, and try different combinations of sending and receiving text and binary data on both iOS and Android. Closes facebook#6889 Differential Revision: D3184835 Pulled By: mkonicek fb-gh-sync-id: f21707f4e97aa5a79847f5157e0a9f132a1a01cd fbshipit-source-id: f21707f4e97aa5a79847f5157e0a9f132a1a01cd
1 parent 0fa48c0 commit ebb44d2

File tree

8 files changed

+441
-163
lines changed

8 files changed

+441
-163
lines changed

Examples/UIExplorer/UIExplorerList.android.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,10 @@ const APIExamples = [
174174
key: 'VibrationExample',
175175
module: require('./VibrationExample'),
176176
},
177+
{
178+
key: 'WebSocketExample',
179+
module: require('./WebSocketExample'),
180+
},
177181
{
178182
key: 'XHRExample',
179183
module: require('./XHRExample'),

Examples/UIExplorer/UIExplorerList.ios.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,10 @@ var APIExamples: Array<UIExplorerExample> = [
248248
key: 'VibrationExample',
249249
module: require('./VibrationExample'),
250250
},
251+
{
252+
key: 'WebSocketExample',
253+
module: require('./WebSocketExample'),
254+
},
251255
{
252256
key: 'XHRExample',
253257
module: require('./XHRExample.ios'),
Lines changed: 286 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,286 @@
1+
/**
2+
* The examples provided by Facebook are for non-commercial testing and
3+
* evaluation purposes only.
4+
*
5+
* Facebook reserves all rights not expressly granted.
6+
*
7+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8+
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9+
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
10+
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
11+
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
12+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13+
*
14+
* @flow
15+
*/
16+
'use strict';
17+
18+
/* eslint-env browser */
19+
20+
const React = require('react');
21+
const ReactNative = require('react-native');
22+
const {
23+
PixelRatio,
24+
StyleSheet,
25+
Text,
26+
TextInput,
27+
TouchableOpacity,
28+
View,
29+
} = ReactNative;
30+
31+
const DEFAULT_WS_URL = 'ws://localhost:5555/';
32+
const WS_EVENTS = [
33+
'close',
34+
'error',
35+
'message',
36+
'open',
37+
];
38+
const WS_STATES = [
39+
/* 0 */ 'CONNECTING',
40+
/* 1 */ 'OPEN',
41+
/* 2 */ 'CLOSING',
42+
/* 3 */ 'CLOSED',
43+
];
44+
45+
class Button extends React.Component {
46+
render(): ReactElement {
47+
const label = <Text style={styles.buttonLabel}>{this.props.label}</Text>;
48+
if (this.props.disabled) {
49+
return (
50+
<View style={[styles.button, styles.disabledButton]}>
51+
{label}
52+
</View>
53+
);
54+
}
55+
return (
56+
<TouchableOpacity
57+
onPress={this.props.onPress}
58+
style={styles.button}>
59+
{label}
60+
</TouchableOpacity>
61+
);
62+
}
63+
}
64+
65+
class Row extends React.Component {
66+
render(): ReactElement {
67+
return (
68+
<View style={styles.row}>
69+
<Text>{this.props.label}</Text>
70+
<Text>{this.props.value}</Text>
71+
</View>
72+
);
73+
}
74+
}
75+
76+
function showValue(value) {
77+
if (value === undefined || value === null) {
78+
return '(no value)';
79+
}
80+
console.log('typeof Uint8Array', typeof Uint8Array);
81+
if (typeof ArrayBuffer !== 'undefined' &&
82+
typeof Uint8Array !== 'undefined' &&
83+
value instanceof ArrayBuffer) {
84+
return `ArrayBuffer {${Array.from(new Uint8Array(value))}}`;
85+
}
86+
return value;
87+
}
88+
89+
type State = {
90+
url: string;
91+
socket: ?WebSocket;
92+
socketState: ?number;
93+
lastSocketEvent: ?string;
94+
lastMessage: ?string | ?ArrayBuffer;
95+
outgoingMessage: string;
96+
};
97+
98+
class WebSocketExample extends React.Component<any, any, State> {
99+
100+
static title = 'WebSocket';
101+
static description = 'WebSocket API';
102+
103+
state: State = {
104+
url: DEFAULT_WS_URL,
105+
socket: null,
106+
socketState: null,
107+
lastSocketEvent: null,
108+
lastMessage: null,
109+
outgoingMessage: '',
110+
};
111+
112+
_connect = () => {
113+
const socket = new WebSocket(this.state.url);
114+
WS_EVENTS.forEach(ev => socket.addEventListener(ev, this._onSocketEvent));
115+
this.setState({
116+
socket,
117+
socketState: socket.readyState,
118+
});
119+
};
120+
121+
_disconnect = () => {
122+
if (!this.state.socket) {
123+
return;
124+
}
125+
this.state.socket.close();
126+
};
127+
128+
// Ideally this would be a MessageEvent, but Flow's definition
129+
// doesn't inherit from Event, so it's 'any' for now.
130+
// See https://github.com/facebook/flow/issues/1654.
131+
_onSocketEvent = (event: any) => {
132+
const state: any = {
133+
socketState: event.target.readyState,
134+
lastSocketEvent: event.type,
135+
};
136+
if (event.type === 'message') {
137+
state.lastMessage = event.data;
138+
}
139+
this.setState(state);
140+
};
141+
142+
_sendText = () => {
143+
if (!this.state.socket) {
144+
return;
145+
}
146+
this.state.socket.send(this.state.outgoingMessage);
147+
this.setState({outgoingMessage: ''});
148+
};
149+
150+
_sendBinary = () => {
151+
if (!this.state.socket ||
152+
typeof ArrayBuffer === 'undefined' ||
153+
typeof Uint8Array === 'undefined') {
154+
return;
155+
}
156+
const {outgoingMessage} = this.state;
157+
const buffer = new Uint8Array(outgoingMessage.length);
158+
for (let i = 0; i < outgoingMessage.length; i++) {
159+
buffer[i] = outgoingMessage.charCodeAt(i);
160+
}
161+
this.state.socket.send(buffer);
162+
this.setState({outgoingMessage: ''});
163+
};
164+
165+
render(): ReactElement {
166+
const socketState = WS_STATES[this.state.socketState || -1];
167+
const canConnect =
168+
!this.state.socket ||
169+
this.state.socket.readyState >= WebSocket.CLOSING;
170+
const canSend = !!this.state.socket;
171+
return (
172+
<View style={styles.container}>
173+
<View style={styles.note}>
174+
<Text>Pro tip:</Text>
175+
<Text style={styles.monospace}>
176+
node Examples/UIExplorer/websocket_test_server.js
177+
</Text>
178+
<Text>
179+
{' in the '}
180+
<Text style={styles.monospace}>react-native</Text>
181+
{' directory starts a test server.'}
182+
</Text>
183+
</View>
184+
<Row
185+
label="Current WebSocket state"
186+
value={showValue(socketState)}
187+
/>
188+
<Row
189+
label="Last WebSocket event"
190+
value={showValue(this.state.lastSocketEvent)}
191+
/>
192+
<Row
193+
label="Last message received"
194+
value={showValue(this.state.lastMessage)}
195+
/>
196+
<TextInput
197+
style={styles.textInput}
198+
autoCorrect={false}
199+
placeholder="Server URL..."
200+
onChangeText={(url) => this.setState({url})}
201+
value={this.state.url}
202+
/>
203+
<Button
204+
onPress={this._connect}
205+
label="Connect"
206+
disabled={!canConnect}
207+
/>
208+
<Button
209+
onPress={this._disconnect}
210+
label="Disconnect"
211+
disabled={canConnect}
212+
/>
213+
<TextInput
214+
style={styles.textInput}
215+
autoCorrect={false}
216+
placeholder="Type message here..."
217+
onChangeText={(outgoingMessage) => this.setState({outgoingMessage})}
218+
value={this.state.outgoingMessage}
219+
/>
220+
<View style={styles.buttonRow}>
221+
<Button
222+
onPress={this._sendText}
223+
label="Send as text"
224+
disabled={!canSend}
225+
/>
226+
<Button
227+
onPress={this._sendBinary}
228+
label="Send as binary"
229+
disabled={!canSend}
230+
/>
231+
</View>
232+
</View>
233+
);
234+
}
235+
236+
}
237+
238+
const styles = StyleSheet.create({
239+
container: {
240+
flex: 1,
241+
},
242+
note: {
243+
padding: 8,
244+
margin: 4,
245+
backgroundColor: 'white',
246+
},
247+
monospace: {
248+
fontFamily: 'courier',
249+
fontSize: 11,
250+
},
251+
row: {
252+
height: 40,
253+
padding: 4,
254+
backgroundColor: 'white',
255+
flexDirection: 'row',
256+
justifyContent: 'space-between',
257+
alignItems: 'center',
258+
borderBottomWidth: 1 / PixelRatio.get(),
259+
borderColor: 'grey',
260+
},
261+
button: {
262+
margin: 8,
263+
padding: 8,
264+
borderRadius: 4,
265+
backgroundColor: 'blue',
266+
alignSelf: 'center',
267+
},
268+
disabledButton: {
269+
opacity: 0.5,
270+
},
271+
buttonLabel: {
272+
color: 'white',
273+
},
274+
buttonRow: {
275+
flexDirection: 'row',
276+
justifyContent: 'center',
277+
},
278+
textInput: {
279+
height: 40,
280+
backgroundColor: 'white',
281+
margin: 8,
282+
padding: 8,
283+
},
284+
});
285+
286+
module.exports = WebSocketExample;
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* The examples provided by Facebook are for non-commercial testing and
3+
* evaluation purposes only.
4+
*
5+
* Facebook reserves all rights not expressly granted.
6+
*
7+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8+
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9+
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
10+
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
11+
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
12+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13+
*
14+
* @flow
15+
*/
16+
'use strict';
17+
18+
/* eslint-env node */
19+
20+
const WebSocket = require('ws');
21+
22+
console.log(`\
23+
Test server for WebSocketExample
24+
25+
This will send each incoming message right back to the other side.a
26+
Restart with the '--binary' command line flag to have it respond with an
27+
ArrayBuffer instead of a string.
28+
`);
29+
30+
const respondWithBinary = process.argv.indexOf('--binary') !== -1;
31+
const server = new WebSocket.Server({port: 5555});
32+
server.on('connection', (ws) => {
33+
ws.on('message', (message) => {
34+
console.log('Received message: %s', message);
35+
if (respondWithBinary) {
36+
message = new Buffer(message);
37+
}
38+
ws.send(message);
39+
});
40+
41+
console.log('Incoming connection!');
42+
ws.send('Why hello there!');
43+
});

0 commit comments

Comments
 (0)