node's net API in React Native
-
Create a new react-native project. Check react-native getting started
-
In your project dir:
npm install @staltz/react-native-tcp --save
Update the following line with your path to node_modules/
and add it to your
podfile:
pod 'TcpSockets', :path => '../node_modules/react-native-tcp'
react-native link @staltz/react-native-tcp
Due to limitations in the react-native packager, streams need to be hacked in with rn-nodeify
- install rn-nodeify as a dev-dependency
npm install --save-dev rn-nodeify
- run rn-nodeify manually
rn-nodeify --install stream,process,util --hack
- optionally you can add this as a postinstall script
"postinstall": "rn-nodeify --install stream,process,util --hack"
only if you want to write require('net') or require('tls') in your javascript
{
"react-native": {
"net": "@staltz/react-native-tcp",
"tls": "@staltz/react-native-tcp/tls"
}
}
see/run index.ios.js/index.android.js for a complete example, but basically it's just like net
var net = require('net');
var net = require('tls');
// OR, if not shimming via package.json "react-native" field:
// var net = require('@staltz/react-native-tcp')
// var tls = require('@staltz/react-native-tcp/tls')
var server = net.createServer(function(socket) {
socket.write('excellent!');
}).listen(12345);
var client = net.createConnection(12345);
client.on('error', function(error) {
console.log(error)
});
client.on('data', function(data) {
console.log('message was received', data)
});
TLS is only supported in the client interface. To use TLS, use the tls.connect()
syntax and not socket = new tls.Socket()
syntax.
const socket = tls.connect({port: 50002, host:'electrum.villocq.com', rejectUnauthorized: false}, () => {
socket.write('{ "id": 5, "method": "blockchain.estimatefee", "params": [2] }\n')
console.log('Connected')
})
socket.on('data', (data) => {
console.log('data:' + data.toString('ascii'))
})