I have the following example of listening to connection and data events, to echo the result back to other telnet clients listening on port 8888. My telnet sessions connect to locahost fine, but no output is echoed. I am hitting my head against a brick wall trying to figure out what is wrong. The execution doesn't even get as far as the 'connect' event.
/server.js
var events = require('events');
var net = require('net');
var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};
channel.on('join', function (id, client) {
this.clients[id] = client;
this.subscriptions[id] = function (senderId, message) {
if (id != senderId) {
this.clients[id].write(message);
}
}
this.on('broadcast', this.subscriptions[id]);
});
var server = net.createServer(function (client) {
var id = client.remoteAddress + ':' + client.remotePort;
console.log(id);
client.on('connect', function () {
console.log('A new connection was made');
channel.emit('join', id, client);
});
client.on('data', function (data) {
data = data.toString();
channel.emit('broadcast', id, data);
});
});
server.listen(8888);
I then run in the command line
node server.js
telnet 127.0.0.1 8888
To fire an event, use the emit() method.
By definition, NodeJS is an event-driven non-blocking runtime environment for JavaScript that has become very popular on the server-side. This is because Nodejs has an event-driven architecture capable of asynchronous I/O.
Emitting events: Every event is named event in nodejs. We can trigger an event by emit(event, [arg1], [arg2], […]) function. We can pass an arbitrary set of arguments to the listener functions.
In Node. js there are two types of threads: one Event Loop (aka the main loop, main thread, event thread, etc.), and a pool of k Workers in a Worker Pool (aka the threadpool). If a thread is taking a long time to execute a callback (Event Loop) or a task (Worker), we call it "blocked".
When the callback to net.createServer
is called, that's because of an implicit connection
event. So your code should look like this:
var server = net.createServer(function (client) {
// when this code is run, the connection has been established
var id = client.remoteAddress + ':' + client.remotePort;
console.log('A new connection was made:', id);
channel.emit('join', id, client);
client.on('data', function(data) {
...
});
client.on('end', function() {
...
});
});
The manual has this to say;
net.createServer([options], [connectionListener])
Creates a new TCP server. The connectionListener argument is automatically set as a listener for the 'connection' event.
In other words, your function (client) {
already received the connection event, and adding a listener to it when it has already been dispatched has no further effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With