Send and Receive packets in NodeJS

0

Well, I'll try to explain the situation:

I'm studying NodeJS and for that I decided to rewrite the server-side code of an application that was originally written in C / C ++, and that server receives packets in hexadecimal from the client application, the question is: how to receive those packets (packets) in NodeJS?

I created a socket for the connection, but I put a lock on it, it follows the code:

var port = process.env.PORT || 8281;
var io = require('socket.io')(port);

io.on('connection', function (socket) {
     var address = socket.handshake;
    console.log('Nova conexão de: ' + JSON.stringify(address, null, 4));
});
    
asked by anonymous 03.09.2016 / 07:07

1 answer

1

The basic class of node.js used for communication in TCP is called "net".

Below is an example of a server and client made with the "net" class. The original (with comments) are on link

server

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 6969;

net.createServer(function(sock) {
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
    sock.on('data', function(data) {
        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        sock.write('You said "' + data + '"');
    });
    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

client

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 6969;

var client = new net.Socket();
client.connect(PORT, HOST, function() {
    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    client.write('I am Chuck Norris!');
});

client.on('data', function(data) {
    console.log('DATA: ' + data);
    client.destroy();
});

client.on('close', function() {
    console.log('Connection closed');
});
03.09.2016 / 15:51