How to connect to RouterOS via Nodejs WebSocket? - node.js

I'm learning websocket nodejs, I want to connect to routeros via websocket like the https://github.com/aluisiora/node-routeros/ package, the package is too broad, I just want to know how to connect.
I've read the official documentation https://wiki.mikrotik.com/wiki/Manual:API, but I'm having trouble understanding it.
I have tried it this way, but did not get any response:
client.connect(port, host, function () {
console.log("Connected");
client.write(encodeString("/login"));
client.write(encodeString(`=name=${user}`));
client.write(encodeString(`=password=${password}`));
});
client.on("data", function (data) {
console.log("Received: " + data); // not excetue
});
I'm looking for code samples to connect to routeros via nodejs socket, hopefully someone shares here.
Thanks in advance, I really appreciate any answer.

Take into consideration the next things:
RouterOS API has it's own protocol, it has a bit of complexity. The official wiki tell us how to interact with it at LOW LEVEL. For these reason it's very difficult to understand. Isn't for a High Level programmer. Don't worry, We have all been through here.
Routeros v7 have a REST API, that will make the job easier, the exchange language is HTTP protocol, easy right? Actually is at beta stage.
RouterOS Wiki have other package for node.js that seems more easy: Mikronode
solution
Install mikronode package
$ npm install mikronode
use it:
var api = require('mikronode');
var connection = new api('192.168.0.1','admin','password');
connection.connect(function(conn) {
var chan=conn.openChannel();
chan.write('/ip/address/print',function() {
chan.on('done',function(data) {
var parsed = api.parseItems(data);
parsed.forEach(function(item) {
console.log('Interface/IP: '+item.interface+"/"+item.address);
});
chan.close();
conn.close();
});
});
});

Related

How to watch for the bitcoin transactions over blockchain via nodejs?

I am using this bitcore npm package.
https://bitcore.io/api/lib
And i want to monitor all the transactions over the blockchain, and read the input address, output address and amount associated with that transaction.
But i am unable to find the javascript method to invoke to accomplish this.
Even i am not able to find a example for this.
I am looking for as short as something like
var someLib = require('some-bitcore-lib')
someLib.on('transaction-found', function(){
// print everything
console.log(arguments);
// do something else;
})
Any help?
Where can i find that some-bitcore-lib or how can i create that in nodejs?
Using a third-party API, as the accepted answers suggests, will work in the short-term. But if you're looking for a long-term, reliable, not-rate-limited solution; you should run your own bitcoin node. It, of course, depends on your project's requirements.
For a robust solution to the OP's question, I suggest the following:
Run a pruned bitcoin node using bitcoind
Enable the ZeroMQ interface of bitcoind with the configuration option zmqpubrawtx=tcp://127.0.0.1:3600. This will enable streaming of raw transaction data to your node.js application
Use the ZeroMQ node.js module to subscribe to the bitcoind's ZeroMQ interface
Use bitcoinjs-lib to decode the raw transaction data
The following node.js example will use zeromq to subscribe to bitcoind's zeromq interface. Then bitcoinjs-lib is used to decode those raw transactions.
var bitcoin = require('bitcoinjs-lib');
var zmq = require('zeromq');
var sock = zmq.socket('sub');
var addr = 'tcp://127.0.0.1:3600';
sock.connect(addr);
sock.subscribe('rawtx');
sock.on('message', function(topic, message) {
if (topic.toString() === 'rawtx') {
var rawTx = message.toString('hex');
var tx = bitcoin.Transaction.fromHex(rawTx);
var txid = tx.getId();
tx.ins = tx.ins.map(function(in) {
in.address = bitcoin.address.fromOutputScript(in.script, bitcoin.networks.bitcoin);
return in;
});
tx.outs = tx.outs.map(function(out) {
out.address = bitcoin.address.fromOutputScript(out.script, bitcoin.networks.bitcoin);
return out;
});
console.log('received transaction', txid, tx);
}
});
For more details, please have a look at this guide
If you don't have your own node you can use blockchain.info APIs as described in here (https://github.com/blockchain/api-v1-client-node/tree/master/Socket)
const Socket = require('blockchain.info/Socket');
const mySocket = new Socket();
mySocket.onTransaction(function() {
console.log(arguments);
});
You can always watch transactions by running your own node without the need to depend on a service like blockchain.info... For example, if you are using btcd (Golang) (https://github.com/btcsuite/btcd) then you can get notified on transactions like in here (http://godoc.org/github.com/btcsuite/btcrpcclient#Client.NotifyNewTransactions)
I think this is what you're looking for. The tutorial helps the user set up a local btc node and demonstrates how to use a zmq subscription along with RPC comms to accomplish sending and receiving transactions as well as notifications and other functionality.
#c.hill's response is correct but leaves out the more complicated functionality described here :)

StrongLoop Websockets

I need a real-time data to be streamed by a client app. Does StrongLoop (or any StrongLoop component) supports websockets-based CRUD. Consider this image:
Please advise.
I'm not sure if I understand correctly, but in my opinion it's totally doable. In your image, there is an intermediate layer between your client app and your API. Assuming such layer exists, it should call your API's endpoints whenever a given event is emitted in your client app.
I would suggest using http://socket.io/ and plain old http://expressjs.com/ with http://visionmedia.github.io/superagent/ for you intermediate layer.
Something like this:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var request = require('superagent');
app.listen(80);
io.on('connection', function (socket) {
socket.on('eventOne', function (data) {
request
.get('/yourapiurl/someresource')
.end(function(err, res){
socket.emit('get-someresource', res.body);
});
});
});
I wouldn't suggest using websockets in the same Strongloop project because, I don't know how complex your API is. This may increase your API complexity and lower your API maintainability.
BTW. You didn't mention what type of data you are trying to send via websockets.

Connecting to socket.io 1.x manually using websockets, capacity testing

I am working with a nodejs express server which uses socket.io to communicate an iOS client, and am having a little trouble trying to test how many clients can connect and exchange data at any one time.
My goal is to be able to run a script which connects to socket.io with thousands of different sessions, as well as send and receive data to understand our system's scale. Currently we are using a single dyno on Heroku but will likely be considering other options on AWS soon.
I have found code which should do what I am trying to do for earlier versions of socket.io, such as this, but have had issues since it seems v1.x has a very different handshake protocol. I tried out using the socket.io-client package, but trying to connect multiple times only simulates use of one session, I need to simulate many in independent users.
I have been picking apart the socket.io-client code, but have only gotten so far as creating a connection - I am stuck on the sending data part. If anyone has any knowledge or could point to some written resources on how data is sent between a client and a socket.io server, it would help me out a lot.
Here's what I have so far:
var needle = require('needle'),
WebSocket = require('ws'),
BASE_URL = 'url-to-socket-host:5002';
var connectionNo = 0;
needle.get('http://' + BASE_URL + '/socket.io/?EIO=3&transport=polling&t=1416506501335-0', function (err, resp) {
// parse the sid
var resp = JSON.parse(resp.body.toString().substring(5, resp.body.toString().length));
// use the sid to connect using websockets
var url = 'ws://' + BASE_URL + '/socket.io/?EIO=3&transport=websocket&sid=' + resp.sid;
console.log(connectionNo + ' with sid: ' + resp.sid);
var socket = new WebSocket(url, void(0), {
agent: false
});
socket.on('open', function () {
console.log('Websocket connected: ' + connectionNo);
// I don't understand how to send data to the server here,
// from looking at the source code it should use some kind
// of binary encoding, any ideas?
socket.on('message', function (msg) {
console.log(msg);
});
});
});
I will continue deconstructing the socket.io-client code but if anyone has any clues or recourses that may help, let me know. Thanks.
I ended up setting for using the socket.io-client npm package which has the ability to connect to a new session on every connection. I found an example benchmark in this issue.
There is not so much need for me to manually connect to socket.io using pure websockets and HTTP, but thanks to Yannik for pointing out the parser in use. The spec of the inner workings of v1.x can be found here.
Thanks!
The problem my reside in the fact that you are not using socket.io in your client code. You have imported ('ws') which is another module whose docs are here: https://www.npmjs.org/package/ws.
You probably want to ws.send('something');. When you receive a message in ws, it also comes with an object with a property indicating whether it is binary data or not. If it is, you will need to concatenate the chunks incrementally. There is a canonical way to do this which you can find via google. But it looks a little like this:
var message;
socketConnection.on('data', function(chunk){ message += chunk});

RabbitMQ and Sails.js

I'm having trouble using RabbitMQ with my Sails app. I'm unsure of where to place the subscriber code. What I'm trying to do is build a notifications system so that when an administrator approves a user's data request, the user's dashboard will pop a notification similar to how Facebook pops a notification. The problem is, putting the subscriber code in my dashboard controller's display route seems to never grab a published message.
Any advice would be greatly appreciated. Currently using rabbit.js package to connect to RabbitMQ.
To answer the original question, if one for some reason wanted to use Rabbit MQ instead of Sails' built-in resourceful pubsub, the best thing would be to use rabbit.js.
First, npm install rabbit.js.
Then, in your Sails project's config/sockets.js (borrowed liberally from the rabbit.js socket.io example):
var context = require('rabbit.js').createContext();
module.exports = {
onConnect: function(session, socket) {
var pub = context.socket('PUB');
var sub = context.socket('SUB');
socket.on('disconnect', function() {
pub.close();
sub.close();
});
// NB we have to adapt between the APIs
sub.setEncoding('utf8');
socket.on('message', function(msg) {
pub.write(msg, 'utf8');
});
sub.on('data', function(msg) {
socket.send(msg);
});
sub.connect('chat');
pub.connect('chat');
}
}
Here's an npm package that implements a RabbitMQ adapter for SailsJS.

DNode implementation for websocket communication in node.js

I don't understand the way DNode uses websocket communication.
Some say it uses socket.io others say sockjs.
Which one is it? Or is it possible to choose?
I'm trying to use DNode, but I also need access to the connections for (semi-)broadcasting in reaction to RPC calls. How do I do this?
Is there a more extensive manual on dnode somewhere?
Your question is kind of vague. I'm not exactly sure whether DNode uses socket.io or sockjs, not sure it even uses one of those based on their dependencies list, but that is not really important when you program it.
As for using connections with DNode, it is pretty straight forward. Here's an example:
var server = dnode({
pushMessageNotification: function(message, cb) {
contact = getClientFromId(message.receiver);
contact.socket.emit('messageNotification', {
message: message.message,
sender: message.sender,
time: message.time
});
cb('success');
}
});
So as you can see, pushMessageNotification is a method that I binded with DNode-PHP and the message is encoded in JSON through PHP. Afterward, all you need is a method to find the socket of the client based on its id.

Resources