Search code examples
node.jstcpsocket

how to add custom event handler?


can i add custom event handler in tcpsocket in 'net' core module in nodejs? something like this

// Import net module.
var net = require('net');

// Create and return a net.Server object,
var server = net.createServer(function(client) {

    client.setEncoding('utf-8');
client.on('event1', function (data) {

console.log(data);
});
});

then emit this event by client if not can i use on('data',callback); and use data event to emit json string and handle it


Solution

  • You can listen for and emit events of any name on any event emitter. But unless you have some code which emits the event you are listening for, such as server.emit('event1', data), the listener won't be called.