react-native-tcp/examples/rctsockets/index.js

96 lines
2.0 KiB
JavaScript
Raw Normal View History

2015-12-23 18:56:33 +00:00
/**
* Copyright (c) 2015-present, Peel Technologies, Inc.
* All rights reserved.
*/
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View
} = React;
global.Buffer = global.Buffer || require('buffer').Buffer;
2015-12-15 00:16:45 +00:00
var net = require('net');
2015-12-15 00:16:45 +00:00
function randomPort() {
2015-12-22 23:53:08 +00:00
return Math.random() * 60536 | 0 + 5000; // 60536-65536
2015-12-15 00:16:45 +00:00
}
2015-12-23 23:14:41 +00:00
var serverPort = randomPort();
2015-12-23 23:14:41 +00:00
var server = net.createServer(function(socket) {
console.log('server connected on ' + JSON.stringify(socket.address()));
2015-12-22 23:53:08 +00:00
socket.on('data', function (data) {
console.log('Server Received: ' + data);
socket.write('Echo server\r\n');
});
2015-12-22 23:53:08 +00:00
socket.on('error', function(error) {
console.log('error ' + error);
});
}).listen(serverPort, function() {
2015-12-23 23:14:41 +00:00
console.log('opened server on ' + JSON.stringify(server.address()));
});
server.on('error', function(error) {
console.log('error ' + error);
});
var client = net.createConnection(serverPort, function() {
2015-12-23 23:14:41 +00:00
console.log('opened client on ' + JSON.stringify(client.address()));
client.write('Hello, server! Love, Client.');
2015-12-22 23:53:08 +00:00
});
2015-12-23 23:14:41 +00:00
client.on('data', function(data) {
console.log('Client Received: ' + data);
2015-12-23 23:14:41 +00:00
client.destroy(); // kill client after server's response
server.close();
2015-12-22 23:53:08 +00:00
});
client.on('error', function(error) {
console.log('client error ' + error);
});
client.on('close', function() {
console.log('client close');
});
var rctsockets = React.createClass({
render: function() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Open Dev Tools to see socket chatter
</Text>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('rctsockets', () => rctsockets);