Sending and Receiving Packages (packets) in Nodejs

Asked

Viewed 413 times

0

Well, I’ll try to explain the situation:

I am studying Nodejs and for this I decided to rewrite the server-side code of an application that was originally written in C/C++, and this server receives packages (packets) in hexadecimal of the client application, the question is: how to receive these packets (packets) in Nodejs ?

I came to create a socket for the connection but I gave a lock, follow the code done:

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));
});
  • Can you show the full code so we can test it too? Without seeing the rest of the application and the client part we don’t know what the problem might be. What was the problem you had? Some mistake or just "nothing happens"?

1 answer

1


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

Below is an example of server and client made with the "net" class. The original (with comments) is in http://www.hacksparrow.com/tcp-socket-programming-in-node-js.html


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');
});

  • Thank you very much José X, it was exactly what I needed to give better progress in what I am doing, perfect answer!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.