Skip to content

Instantly share code, notes, and snippets.

@mattneary
Created November 24, 2012 03:48
Show Gist options
  • Save mattneary/4138269 to your computer and use it in GitHub Desktop.
Save mattneary/4138269 to your computer and use it in GitHub Desktop.
Node.js Telnet Chat
// To Access Once Running: `telnet localhost 8124`
var net = require('net');
var users = [];
var red = '\033[31m'; // command line colors
var reset = '\033[0m';
var server = net.createServer(function(c) {
// handle new connection
c.on('end', function() {
console.log("end");
// when connection ends, remove from user list
users = users.filter(function(user) {
return user.conn != c;
});
});
c.write('Welcome! Enter a username: ');
// add a new user
var newUser = {
conn: c,
name: "<n/a>"
};
users.push(newUser);
var buffer = "";
var handler = {
emit: function() {},
on: function() {},
removeListener: function() {},
destroy: function() {},
end: function() {},
write: function(statement) {
if( statement == "\r\n" ){
statement = buffer;
buffer = "";
console.log("end");
// handle messages
if( newUser.name == "<n/a>" ) {
// make their first message their username
newUser.name = (""+statement).replace(/\s/g, '');
newUser.conn.write('> ');
} else if( (statement+"").indexOf('\u0004') == -1 ) {
// if this isn't merely an end statement, send it to others
// ... and display on the senders screen as `ME:...`
users.map(function(user) {
if( user != newUser ) {
user.conn.write(red+newUser.name+reset+": "+statement+"\r\n");
} else {
user.conn.write("> "+red+"ME"+reset+": "+statement+"\r\n");
}
user.conn.write("> ");
});
}
} else {
buffer += statement;
}
},
writable: true
};
// feed messages through our handler
newUser.conn.pipe(handler);
});
server.listen(8124);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment