react-native-udp/index.ios.js

107 lines
2.2 KiB
JavaScript
Raw Normal View History

2015-05-09 21:55:49 +00:00
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
} = React;
2015-05-10 14:26:29 +00:00
// require('./test/simple/test-dgram-address')
// require('./test/simple/test-dgram-bind-default-address')
// require('./test/simple/test-dgram-bind-shared-ports')
2015-05-09 21:55:49 +00:00
function randomPort() {
2015-07-05 20:44:02 +00:00
return Math.random() * 60536 | 0 + 5000 // 60536-65536
2015-05-09 21:55:49 +00:00
}
var base64 = require('base64-js')
var dgram = require('dgram')
2015-05-09 21:55:49 +00:00
var a = dgram.createSocket('udp4')
var aPort = randomPort()
2015-07-05 20:44:02 +00:00
a.bind(aPort, function(err) {
2015-05-09 21:55:49 +00:00
if (err) throw err
console.log('address', a.address())
})
var b = dgram.createSocket('udp4')
var bPort = randomPort()
b.bind(bPort, function(err) {
if (err) throw err
console.log('address', b.address())
})
a.on('message', function(data, rinfo) {
var str = String.fromCharCode.apply(null, new Uint8Array(data));
console.log('a received', str, rinfo)
a.close()
b.close()
})
b.on('message', function(data, rinfo) {
var str = String.fromCharCode.apply(null, new Uint8Array(data));
console.log('b received', str, rinfo)
// echo back
b.send(data, 0, data.length, aPort, '127.0.0.1', function(err) {
if (err) throw err
console.log('sent')
})
})
b.once('listening', function() {
var msg = toByteArray('hello')
a.send(msg, 0, msg.length, bPort, '127.0.0.1', function(err) {
if (err) throw err
console.log('sent')
})
})
var rctsockets = React.createClass({
render: function() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
2015-05-10 14:59:44 +00:00
Open Dev Tools to see socket chatter
2015-05-09 21:55:49 +00:00
</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,
},
});
// only works for 8-bit chars
2015-05-09 21:55:49 +00:00
function toByteArray(obj) {
var uint = new Uint8Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++){
uint[i] = obj.charCodeAt(i);
}
return new Uint8Array(uint);
}
AppRegistry.registerComponent('react-native-udp', () => rctsockets);