Created
July 29, 2011 08:07
-
-
Save frosas/1113425 to your computer and use it in GitHub Desktop.
A simple chat on node.js. Based on Ryan Dahl presentation example (http://www.youtube.com/watch?v=jo_B4LTHi3I)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var net = require('net') | |
var users = (function() { | |
var users = [] | |
return { | |
add: function(socket) { | |
var user = new User(this, socket) | |
users.push(user) | |
user.sendOthers("# User joined\n") | |
return user | |
}, | |
remove: function(user) { | |
var i = users.indexOf(user) | |
if (i == -1) throw "User not found" | |
user.sendOthers("# User left\n") | |
users.splice(i, 1) | |
}, | |
all: function() { | |
return users | |
} | |
} | |
})() | |
var User = function(users, socket) { | |
return { | |
sendOthers: function(message) { | |
var _users = users.all() | |
for (var i = 0; i < _users.length; i++) { | |
if (_users[i] == this) continue | |
_users[i].send(message) | |
} | |
}, | |
send: function(message) { | |
socket.write(message) | |
}, | |
leave: function() { | |
users.remove(this) | |
} | |
} | |
} | |
net.createServer(function(socket) { | |
var user = users.add(socket) | |
socket.on('data', function(data) { | |
user.sendOthers("> " + data) | |
}) | |
socket.on('close', function(hadError) { | |
user.leave() | |
}) | |
}).listen(8000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment