0

I'm trying the understand the correct way to communicate between a client sending data to a node.js server via TCP connection.

The client is a small electronic device able to create a TCP socket to communicate with the internet.

The remote server is running node.js supported by a mongodb database.

What is the better way to communicate?

I don't have much experience but some ideias come to mind:

  • I could send http POST to the server, filter the message and redirect the content to the database.
  • Run a dedicated TCP server in the http server on a different port and connect directly to this server.

Another question is where to put security? should the client send encrypted messages to be decoded at the server?

Thank you very much

masp
  • 3
  • 1
  • 2

2 Answers2

1

If you want to communicate between server and client on port you need to create tcp connection on server.

In tcp connection way of communication is different rather than http request. If your device send to data on port it will receive on a dedicated server along with defined port.

In node.js for tcp connection we need to require 'net' module

var net = require("net");

To create server following line would be used

var server = net.createServer({allowHalfOpen: true});

we need to written following lines to receive client side request on dedicated port.

server.on('connection', function(stream) {

});
server.listen(6969);

Here 6969 is the port.

Full snippet given below to create server of tcp connection.

// server.js

var net = require("net");
global.mongo = require('mongoskin');
var serverOptions = {
    'native_parser': true,
    'auto_reconnect': true,
    'poolSize': 5
};
var db = mongo.db("mongodb://127.0.0.1:27017/testdb", serverOptions);
var PORT = '6969';
var server = net.createServer({allowHalfOpen: true}); 
// listen connection request from client side
server.on('connection', function(stream) {
    console.log("New Client is connected on " + stream.remoteAddress + ":" + stream.remotePort);
    stream.setTimeout(000);
    stream.setEncoding("utf8");
    var data_stream = '';

    stream.addListener("error", function(err) {
        if (clients.indexOf(stream) !== -1) {
            clients.splice(clients.indexOf(stream), 1);
        }
        console.log(err);
    });

    stream.addListener("data", function(data) {
        var incomingStanza;
        var isCorrectJson = false;
        db.open(function(err, db) {
            if (err) {
                AppFun.errorOutput(stream, 'Error in connecting database..');
            } else {
                stream.name = stream.remoteAddress + ":" + stream.remotePort;
                // Put this new client in the list
                clients.push(stream);
                console.log("CLIENTS LENGTH " + clients.length);
                //handle json whether json is correct or not
                try {
                    var incomingStanza = JSON.parse(data);
                    isCorrectJson = true;
                } catch (e) {
                    isCorrectJson = false;
                }
            // Now you can process here for each request of client

    });
    stream.addListener("end", function() {
        stream.name = stream.remoteAddress + ":" + stream.remotePort;
        if (clients.indexOf(stream) !== -1) {
            clients.splice(clients.indexOf(stream), 1);
        }
        console.log("end of listener");
        stream.end();
        stream.destroy();
    });

});
server.listen(PORT);

console.log("Vent server listening on post number " + PORT);
// on error this msg will be shown
server.on('error', function(e) {
    if (e.code == 'EADDRINUSE') {
        console.log('Address in use, retrying...');
        server.listen(5555);
        setTimeout(function() {
            server.close();
            server.listen(PORT);
        }, 1000);
    }
    if (e.code == 'ECONNRESET') {
        console.log('Something Wrong. Connection is closed..');
        setTimeout(function() {
            server.close();
            server.listen(PORT);
        }, 1000);
    }
});

Now its time to create a client for tcp server

From clint we will send all request to make a conncetion get possible results

//client.js

var net = require('net');
var client = net.connect({
    //host:'localhost://', 
    port: 6969
},
function() { //'connect' listener
    console.log('client connected');

 var  jsonData = '{"cmd":"test_command"}';

    client.write(jsonData);
});

client.on('data', function(data) {
    console.log(data.toString());
//    client.end();
});

client.on('end', function() {
    console.log('client disconnected');
});

Now we have both server and client in tcp communication.

to ready to listen server we need to hit command 'node server.js' in console.

after that server will be ready to listen request from client side

to make a call from client we need to hit command 'node client.js'

It will more meaningful and worthy if you can modify according your acctual requirement.

Thanks

Dineshaws
  • 2,065
  • 16
  • 26
  • Than you for such a detailed answer on how to use a dedicated port communication. I'm sure it will be of great help to those who have a similar issue! – masp Apr 02 '15 at 11:00
0

When it comes to security, it is best not to roll your own solution, but rather use software that other (smart) people have verified.

With this in mind, I would send HTTPS requests to the server. Node.js supports supports HTTPS. HTTPS give you two things: the client can verify that the server is actually yours, and the traffic is protected from eavesdropping. The third thing to do is to verify that the client isn't some bad guy. This is harder to do. You could check the client's IP address, or use password based authentication.

Community
  • 1
  • 1
Craig S. Anderson
  • 6,966
  • 4
  • 33
  • 46
  • Thank you, I will try to use HTTPS. Security is not a big issue but it is good to have some kind of it. – masp Apr 02 '15 at 10:57