I am trying to make a telnet chat server using node.js
nothing appears when I open multiple terminals and enter text. i.e. the text is not transmitted to the other terminal
I open serveral terminals and enter
telnet 127.0.0.1 8888
then start typing but nothing appears
var events = require('events');
var net = require('net');
var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};
channel.on('join', function(id, client) {
console.log("join");
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) {
console.log("createServer");
var id = client.remoteAddress + ':' + client.remotePort;
client.on('connect', function() {
console.log("connect");
channel.emit('join', id, client);
});
client.on('data', function(data) {
console.log("data");
data = data.toString();
channel.emit('broadcast', id, data);
});
});
server.listen(8888);
I have simplified (sort of) your code to show how to send messages to users:
var events = require('events');
var net = require('net');
clients = [];
function randomInt (low, high) {
return Math.floor(Math.random() * (high - low) + low);
}
function generateId(length) {
var output = "";
for(var i = 0;i<length;i++) {
output += randomInt(0,9);
}
return output;
}
function sendToAll(data,sender) {
console.log(clients.length);
var size = clients.length;
for(i=0;i<size;i++) {
if(sender.unique_id != clients[i].unique_id) {
clients[i].write(data);
}
}
}
var server = net.createServer(function(client) {
console.log("New client: " + client.remoteAddress);
client.write("Welcome!\r\n");
client.unique_id = generateId(10);
clients.push(client);
client.on('data', function(data) {
data = data.toString();
console.log(data);
sendToAll(data,client);
});
});
server.listen(8888);