Skip to content

Instantly share code, notes, and snippets.

@ryankshaw
Created January 27, 2010 04:48
Show Gist options
  • Save ryankshaw/287544 to your computer and use it in GitHub Desktop.
Save ryankshaw/287544 to your computer and use it in GitHub Desktop.
// if you have node installed on your computer you can run this server by doing
// node path/to/this/file.js
// figure out how to install node-js at http://nodejs.org
var tcp = require('tcp');
var cons = [];
var chat = function(cons, socket, message){
for (var i=0; i < cons.length; i++) {
if (cons[i] != socket) {
cons[i].send(message + "\n");
};
}
};
var server = tcp.createServer(function (socket) {
cons.push(socket);
socket.setEncoding("utf8");
socket.addListener("connect", function () {
socket.send("Welcome to the ghetto chat, what is your username?:\n");
});
socket.addListener("receive", function (data) {
var data = data.trim();
if (!socket.username) {
socket.username = data;
socket.send("welcome " + socket.username + "\n");
chat(cons, socket, socket.username + " has connected to the server.");
}
else if (data.trim() === "/quit") {
socket.send("goodbye\r\n");
socket.close();
cons.splice(cons.indexOf(socket), 1);
chat(cons, socket, socket.username + " has left the server.");
}
else {
chat(cons, socket, socket.username + ": " + data);
}
});
});
server.listen(8002);
// # here is the ruby code that does the same thing
//
//
// require 'socket'
// port = 7890
// server = TCPServer.new(port)
//
// def chat(cons, conn, message)
// cons.each do |c|
// c.puts message unless c == conn
// end
// end
//
// cons = []
// while(connection = server.accept)
// Thread.new(connection) do |conn|
// cons << conn
// conn.puts "Welcome to the ghetto chat, what is your username?:\n"
// name = conn.gets.chomp
// conn.puts "Welcome %s!" % name
//
// chat(cons, conn, "%s has connected to the server." % name)
// while( message = conn.gets.chomp)
// if message == "/quit"
// cons.delete conn
// conn.close
// chat(cons, conn, "%s has left the server." % name)
// break
// end
// chat(cons, conn, "%s: %s" % [name, message])
// end
// end
// end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment