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 https://github.com/facebook/react-native/pull/6889

Differential Revision: D3184835

Pulled By: mkonicek

fb-gh-sync-id: f21707f4e97aa5a79847f5157e0a9f132a1a01cd
fbshipit-source-id: f21707f4e97aa5a79847f5157e0a9f132a1a01cd
This commit is contained in:
Philipp von Weitershausen 2016-04-18 15:42:42 -07:00 committed by Facebook Github Bot 0
parent 0fa48c00a9
commit ebb44d202b
8 changed files with 442 additions and 164 deletions

View File

@ -174,6 +174,10 @@ const APIExamples = [
key: 'VibrationExample',
module: require('./VibrationExample'),
},
{
key: 'WebSocketExample',
module: require('./WebSocketExample'),
},
{
key: 'XHRExample',
module: require('./XHRExample'),

View File

@ -248,6 +248,10 @@ var APIExamples: Array<UIExplorerExample> = [
key: 'VibrationExample',
module: require('./VibrationExample'),
},
{
key: 'WebSocketExample',
module: require('./WebSocketExample'),
},
{
key: 'XHRExample',
module: require('./XHRExample.ios'),

View File

@ -0,0 +1,286 @@
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';
/* eslint-env browser */
const React = require('react');
const ReactNative = require('react-native');
const {
PixelRatio,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
} = ReactNative;
const DEFAULT_WS_URL = 'ws://localhost:5555/';
const WS_EVENTS = [
'close',
'error',
'message',
'open',
];
const WS_STATES = [
/* 0 */ 'CONNECTING',
/* 1 */ 'OPEN',
/* 2 */ 'CLOSING',
/* 3 */ 'CLOSED',
];
class Button extends React.Component {
render(): ReactElement {
const label = <Text style={styles.buttonLabel}>{this.props.label}</Text>;
if (this.props.disabled) {
return (
<View style={[styles.button, styles.disabledButton]}>
{label}
</View>
);
}
return (
<TouchableOpacity
onPress={this.props.onPress}
style={styles.button}>
{label}
</TouchableOpacity>
);
}
}
class Row extends React.Component {
render(): ReactElement {
return (
<View style={styles.row}>
<Text>{this.props.label}</Text>
<Text>{this.props.value}</Text>
</View>
);
}
}
function showValue(value) {
if (value === undefined || value === null) {
return '(no value)';
}
console.log('typeof Uint8Array', typeof Uint8Array);
if (typeof ArrayBuffer !== 'undefined' &&
typeof Uint8Array !== 'undefined' &&
value instanceof ArrayBuffer) {
return `ArrayBuffer {${Array.from(new Uint8Array(value))}}`;
}
return value;
}
type State = {
url: string;
socket: ?WebSocket;
socketState: ?number;
lastSocketEvent: ?string;
lastMessage: ?string | ?ArrayBuffer;
outgoingMessage: string;
};
class WebSocketExample extends React.Component<any, any, State> {
static title = 'WebSocket';
static description = 'WebSocket API';
state: State = {
url: DEFAULT_WS_URL,
socket: null,
socketState: null,
lastSocketEvent: null,
lastMessage: null,
outgoingMessage: '',
};
_connect = () => {
const socket = new WebSocket(this.state.url);
WS_EVENTS.forEach(ev => socket.addEventListener(ev, this._onSocketEvent));
this.setState({
socket,
socketState: socket.readyState,
});
};
_disconnect = () => {
if (!this.state.socket) {
return;
}
this.state.socket.close();
};
// Ideally this would be a MessageEvent, but Flow's definition
// doesn't inherit from Event, so it's 'any' for now.
// See https://github.com/facebook/flow/issues/1654.
_onSocketEvent = (event: any) => {
const state: any = {
socketState: event.target.readyState,
lastSocketEvent: event.type,
};
if (event.type === 'message') {
state.lastMessage = event.data;
}
this.setState(state);
};
_sendText = () => {
if (!this.state.socket) {
return;
}
this.state.socket.send(this.state.outgoingMessage);
this.setState({outgoingMessage: ''});
};
_sendBinary = () => {
if (!this.state.socket ||
typeof ArrayBuffer === 'undefined' ||
typeof Uint8Array === 'undefined') {
return;
}
const {outgoingMessage} = this.state;
const buffer = new Uint8Array(outgoingMessage.length);
for (let i = 0; i < outgoingMessage.length; i++) {
buffer[i] = outgoingMessage.charCodeAt(i);
}
this.state.socket.send(buffer);
this.setState({outgoingMessage: ''});
};
render(): ReactElement {
const socketState = WS_STATES[this.state.socketState || -1];
const canConnect =
!this.state.socket ||
this.state.socket.readyState >= WebSocket.CLOSING;
const canSend = !!this.state.socket;
return (
<View style={styles.container}>
<View style={styles.note}>
<Text>Pro tip:</Text>
<Text style={styles.monospace}>
node Examples/UIExplorer/websocket_test_server.js
</Text>
<Text>
{' in the '}
<Text style={styles.monospace}>react-native</Text>
{' directory starts a test server.'}
</Text>
</View>
<Row
label="Current WebSocket state"
value={showValue(socketState)}
/>
<Row
label="Last WebSocket event"
value={showValue(this.state.lastSocketEvent)}
/>
<Row
label="Last message received"
value={showValue(this.state.lastMessage)}
/>
<TextInput
style={styles.textInput}
autoCorrect={false}
placeholder="Server URL..."
onChangeText={(url) => this.setState({url})}
value={this.state.url}
/>
<Button
onPress={this._connect}
label="Connect"
disabled={!canConnect}
/>
<Button
onPress={this._disconnect}
label="Disconnect"
disabled={canConnect}
/>
<TextInput
style={styles.textInput}
autoCorrect={false}
placeholder="Type message here..."
onChangeText={(outgoingMessage) => this.setState({outgoingMessage})}
value={this.state.outgoingMessage}
/>
<View style={styles.buttonRow}>
<Button
onPress={this._sendText}
label="Send as text"
disabled={!canSend}
/>
<Button
onPress={this._sendBinary}
label="Send as binary"
disabled={!canSend}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
note: {
padding: 8,
margin: 4,
backgroundColor: 'white',
},
monospace: {
fontFamily: 'courier',
fontSize: 11,
},
row: {
height: 40,
padding: 4,
backgroundColor: 'white',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
borderBottomWidth: 1 / PixelRatio.get(),
borderColor: 'grey',
},
button: {
margin: 8,
padding: 8,
borderRadius: 4,
backgroundColor: 'blue',
alignSelf: 'center',
},
disabledButton: {
opacity: 0.5,
},
buttonLabel: {
color: 'white',
},
buttonRow: {
flexDirection: 'row',
justifyContent: 'center',
},
textInput: {
height: 40,
backgroundColor: 'white',
margin: 8,
padding: 8,
},
});
module.exports = WebSocketExample;

View File

@ -0,0 +1,43 @@
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';
/* eslint-env node */
const WebSocket = require('ws');
console.log(`\
Test server for WebSocketExample
This will send each incoming message right back to the other side.a
Restart with the '--binary' command line flag to have it respond with an
ArrayBuffer instead of a string.
`);
const respondWithBinary = process.argv.indexOf('--binary') !== -1;
const server = new WebSocket.Server({port: 5555});
server.on('connection', (ws) => {
ws.on('message', (message) => {
console.log('Received message: %s', message);
if (respondWithBinary) {
message = new Buffer(message);
}
ws.send(message);
});
console.log('Incoming connection!');
ws.send('Why hello there!');
});

View File

@ -11,17 +11,31 @@
*/
'use strict';
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var RCTWebSocketModule = require('NativeModules').WebSocketModule;
const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
const RCTWebSocketModule = require('NativeModules').WebSocketModule;
const Platform = require('Platform');
const WebSocketEvent = require('WebSocketEvent');
var Platform = require('Platform');
var WebSocketBase = require('WebSocketBase');
var WebSocketEvent = require('WebSocketEvent');
const EventTarget = require('event-target-shim');
const base64 = require('base64-js');
var base64 = require('base64-js');
import type EventSubscription from 'EventSubscription';
var WebSocketId = 0;
var CLOSE_NORMAL = 1000;
const CONNECTING = 0;
const OPEN = 1;
const CLOSING = 2;
const CLOSED = 3;
const CLOSE_NORMAL = 1000;
const WEBSOCKET_EVENTS = [
'close',
'error',
'message',
'open',
];
let nextWebSocketId = 0;
/**
* Browser-compatible WebSockets implementation.
@ -29,96 +43,130 @@ var CLOSE_NORMAL = 1000;
* See https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
* See https://github.com/websockets/ws
*/
class WebSocket extends WebSocketBase {
class WebSocket extends EventTarget(WEBSOCKET_EVENTS) {
static CONNECTING = CONNECTING;
static OPEN = OPEN;
static CLOSING = CLOSING;
static CLOSED = CLOSED;
CONNECTING: number = CONNECTING;
OPEN: number = OPEN;
CLOSING: number = CLOSING;
CLOSED: number = CLOSED;
_socketId: number;
_subs: any;
_subscriptions: Array<EventSubscription>;
connectToSocketImpl(url: string, protocols: ?Array<string>, headers: ?Object): void {
this._socketId = WebSocketId++;
onclose: ?Function;
onerror: ?Function;
onmessage: ?Function;
onopen: ?Function;
RCTWebSocketModule.connect(url, protocols, headers, this._socketId);
binaryType: ?string;
bufferedAmount: number;
extension: ?string;
protocol: ?string;
readyState: number = CONNECTING;
url: ?string;
this._registerEvents(this._socketId);
constructor(url: string, protocols: ?string | ?Array<string>, options: ?{origin?: string}) {
super();
if (typeof protocols === 'string') {
protocols = [protocols];
}
if (!Array.isArray(protocols)) {
protocols = null;
}
this._socketId = nextWebSocketId++;
RCTWebSocketModule.connect(url, protocols, options, this._socketId);
this._registerEvents();
}
closeConnectionImpl(code?: number, reason?: string): void {
this._closeWebSocket(this._socketId, code, reason);
close(code?: number, reason?: string): void {
if (this.readyState === this.CLOSING ||
this.readyState === this.CLOSED) {
return;
}
this.readyState = this.CLOSING;
this._close(code, reason);
}
cancelConnectionImpl(): void {
this._closeWebSocket(this._socketId);
send(data: any): void {
if (this.readyState === this.CONNECTING) {
throw new Error('INVALID_STATE_ERR');
}
if (typeof data === 'string') {
RCTWebSocketModule.send(data, this._socketId);
} else if (data instanceof ArrayBuffer) {
console.warn('Sending ArrayBuffers is not yet supported');
} else {
throw new Error('Not supported data type');
}
}
sendStringImpl(message: string): void {
RCTWebSocketModule.send(message, this._socketId);
}
sendArrayBufferImpl(): void {
// TODO
console.warn('Sending ArrayBuffers is not yet supported');
}
_closeWebSocket(id: number, code?: number, reason?: string): void {
_close(code?: number, reason?: string): void {
if (Platform.OS === 'android') {
/*
* See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
*/
// See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
var statusCode = typeof code === 'number' ? code : CLOSE_NORMAL;
var closeReason = typeof reason === 'string' ? reason : '';
RCTWebSocketModule.close(statusCode, closeReason, id);
RCTWebSocketModule.close(statusCode, closeReason, this._socketId);
} else {
RCTWebSocketModule.close(id);
RCTWebSocketModule.close(this._socketId);
}
}
_unregisterEvents(): void {
this._subs.forEach(e => e.remove());
this._subs = [];
this._subscriptions.forEach(e => e.remove());
this._subscriptions = [];
}
_registerEvents(id: number): void {
this._subs = [
_registerEvents(): void {
this._subscriptions = [
RCTDeviceEventEmitter.addListener('websocketMessage', ev => {
if (ev.id !== id) {
if (ev.id !== this._socketId) {
return;
}
var event = new WebSocketEvent('message', {
data: (ev.type === 'binary') ? base64.toByteArray(ev.data).buffer : ev.data
});
this.onmessage && this.onmessage(event);
this.dispatchEvent(event);
}),
RCTDeviceEventEmitter.addListener('websocketOpen', ev => {
if (ev.id !== id) {
if (ev.id !== this._socketId) {
return;
}
this.readyState = this.OPEN;
var event = new WebSocketEvent('open');
this.onopen && this.onopen(event);
this.dispatchEvent(event);
}),
RCTDeviceEventEmitter.addListener('websocketClosed', ev => {
if (ev.id !== id) {
if (ev.id !== this._socketId) {
return;
}
this.readyState = this.CLOSED;
var event = new WebSocketEvent('close');
event.code = ev.code;
event.reason = ev.reason;
this.onclose && this.onclose(event);
this.dispatchEvent(event);
this._unregisterEvents();
this.close();
}),
RCTDeviceEventEmitter.addListener('websocketFailed', ev => {
if (ev.id !== id) {
if (ev.id !== this._socketId) {
return;
}
var event = new WebSocketEvent('error');
event.message = ev.message;
this.onerror && this.onerror(event);
this.onclose && this.onclose(event);
this.dispatchEvent(event);
event = new WebSocketEvent('close');
event.message = ev.message;
this.dispatchEvent(event);
this._unregisterEvents();
this.close();
})

View File

@ -1,115 +0,0 @@
/**
* 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 WebSocketBase
* @flow
*/
'use strict';
var EventTarget = require('event-target-shim');
const CONNECTING = 0;
const OPEN = 1;
const CLOSING = 2;
const CLOSED = 3;
/**
* Shared base for platform-specific WebSocket implementations.
*/
class WebSocketBase extends EventTarget {
CONNECTING: number;
OPEN: number;
CLOSING: number;
CLOSED: number;
onclose: ?Function;
onerror: ?Function;
onmessage: ?Function;
onopen: ?Function;
binaryType: ?string;
bufferedAmount: number;
extension: ?string;
protocol: ?string;
readyState: number;
url: ?string;
constructor(url: string, protocols: ?string | ?Array<string>, options: ?{origin?: string}) {
super();
this.CONNECTING = CONNECTING;
this.OPEN = OPEN;
this.CLOSING = CLOSING;
this.CLOSED = CLOSED;
if (typeof protocols === 'string') {
protocols = [protocols];
}
if (!Array.isArray(protocols)) {
protocols = null;
}
this.readyState = this.CONNECTING;
this.connectToSocketImpl(url, protocols, options);
}
close(): void {
if (this.readyState === this.CLOSING ||
this.readyState === this.CLOSED) {
return;
}
if (this.readyState === this.CONNECTING) {
this.cancelConnectionImpl();
}
this.readyState = this.CLOSING;
this.closeConnectionImpl();
}
send(data: any): void {
if (this.readyState === this.CONNECTING) {
throw new Error('INVALID_STATE_ERR');
}
if (typeof data === 'string') {
this.sendStringImpl(data);
} else if (data instanceof ArrayBuffer) {
this.sendArrayBufferImpl(data);
} else {
throw new Error('Not supported data type');
}
}
closeConnectionImpl(): void {
throw new Error('Subclass must define closeConnectionImpl method');
}
connectToSocketImpl(url: string, protocols: ?Array<string>, options: ?{origin?: string}): void {
throw new Error('Subclass must define connectToSocketImpl method');
}
cancelConnectionImpl(): void {
throw new Error('Subclass must define cancelConnectionImpl method');
}
sendStringImpl(message: string): void {
throw new Error('Subclass must define sendStringImpl method');
}
sendArrayBufferImpl(): void {
throw new Error('Subclass must define sendArrayBufferImpl method');
}
}
WebSocketBase.CONNECTING = CONNECTING;
WebSocketBase.OPEN = OPEN;
WebSocketBase.CLOSING = CLOSING;
WebSocketBase.CLOSED = CLOSED;
module.exports = WebSocketBase;

View File

@ -6,4 +6,13 @@
// problem go away.
'use strict';
module.exports = function() {};
function EventTarget() {
// Support both EventTarget and EventTarget([list, of, events])
// as a super class, just like the original module does.
if (arguments.length === 1 && Array.isArray(arguments[0])) {
return EventTarget;
}
}
module.exports = EventTarget;

View File

@ -4,7 +4,6 @@
'use strict';
jest.dontMock('WebSocket');
jest.dontMock('WebSocketBase');
jest.setMock('NativeModules', {
WebSocketModule: {
connect: () => {}
@ -13,7 +12,7 @@ jest.setMock('NativeModules', {
var WebSocket = require('WebSocket');
describe('WebSocketBase', function() {
describe('WebSocket', function() {
it('should have connection lifecycle constants defined on the class', () => {
expect(WebSocket.CONNECTING).toEqual(0);