Reputation: 9702
Recently I have started learning Node.js with "Node.js in Action" book. In chapter there is following listing:
var events = require('events');
var net = require('net');
var channel = new events.EventEmitter();
channel.clients = {};
channel.subsriptions = {};
channel.on('join', function (id, client) {
this.clients[id] = client;
this.subsriptions[id] = function (senderId, message) {
if (id !== senderId) {
this.clients[id].write(message);
}
};
this.on('broadcast', this.subsriptions[id]);
});
var server = net.createServer(function (client) {
var id = client.remoteAddress + ':' + client.remotePort;
client.on('connect', function () {
channel.emit('join', id, client);
});
client.on('data', function (data) {
data = data.toString();
channel.emit('broadcast', id, data);
});
});
server.listen(8888);
I ran code:
node chat_server.js
Then opened new terminal and connected to chat_sever:
telnet 127.0.0.1 8888
Then again opened new terminal window and connected to chat_server. The book says:
"If you open up a few command lines, you’ll see that anything typed in one command line is echoed to the others. "
I tried to type in one terminal but nothing echoed in others. What can be problem? I am running Ubuntu 12.04
EDIT:
I tried to debug this part:
client.on('connect', function () {
console.log('joined ' + id);
channel.emit('join', id, client);
});
but it does not show me "joined message" even if I open several terminals.
Upvotes: 2
Views: 891
Reputation: 9702
I have solved my problem by the help of this SO question:
on the server side, the socket is already connected when you get the callback, and the event you're trying to listen to isn't emitted on an already connected socket.
So, I emitted 'join' outside of client.on('connect'). In other words this code:
client.on('connect', function () {
channel.emit('join', id, client);
});
does nothing. And it must be replaced by:
channel.emit('join', id, client);
Upvotes: 3