netpoetica
netpoetica

Reputation: 3425

How to distinguish between node socket server / client packets on data event?

In node, when you create a socket server and connect to it with a client, the write function triggers the data event, but it seems there is no way to distinguish the source of the traffic (other than adding your own IDs/headers to each sent buffer).

For example, this is the output "server says hello" from the server.write, and then all of the "n client msg" are from client.write, and they all come out in on('data', fn):

➜  sockets  node client.js 
client connected to server!
client data: server says hello
client data: 1 client msg!
client data: 2 client msg!
client data: 3 client msg!
client data: 4 client msg!

Is there a correct way to distinguish the source of the data on a socket?

The code for a simple client:

// client.js
var net = require('net');
var split = require('split');

var client = net.connect({
  port: 8124
}, function() {
  //'connect' listener
  console.log('client connected to server!');
  client.write('1 client msg!\r\n');
  client.write('2 client msg!\r\n');
  client.write('3 client msg!\r\n');
  client.write('4 client msg!\r\n');
});

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

var stream = client.pipe(split());
stream.on('data', function(data) {
  console.log("client data: " + data.toString());
});

and the code for the server

// server.js
var net = require('net');
var split = require('split');

var server = net.createServer(function(c) { //'connection' listener

    console.log('client connected');

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

    c.write('server says hello\r\n');

    c.pipe(c);

    var stream = c.pipe(split());

    stream.on('data', function(data) {
      console.log("client data: " + data.toString());
    });

});
server.listen(8124, function() { //'listening' listener
    console.log('server bound');
});

Upvotes: 0

Views: 588

Answers (2)

Luciano
Luciano

Reputation: 234

You can distinguish each client with: c.name = c.remoteAddress + ":" + c.remotePort;

c.on('data', function(data) {
   console.log('data ' + data + ' from ' + c.name);
});

Upvotes: 0

mscdex
mscdex

Reputation: 106746

The source of the traffic is the server.

If you're wanting to know whether it's data being echoed back to the client by the server, you will have to come up with your own protocol for denoting that.

For example, the server could respond with newline-delimited JSON data that is prefixed by a special byte that indicates whether it's an echo or an "original" response (or any other kind of "type" value you want to have). Then the client reads a line in, checks the first byte value to know if it's an echo or not, then JSON.parse()s the rest of the line after the first byte.

Upvotes: 0

Related Questions