-
-
Save olalonde/3910332 to your computer and use it in GitHub Desktop.
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 http = require('http'), | |
sys = require('sys'), | |
fs = require('fs'), | |
ws = require('./ws.js'); | |
var clients = []; | |
http.createServer(function(request, response) | |
{ | |
response.writeHead(200, | |
{ | |
'Content-Type': 'text/html' | |
}); | |
var rs = fs.createReadStream(__dirname + '/template.html'); | |
sys.pump(rs, response); | |
}).listen(8080); | |
ws.createServer(function(websocket) | |
{ | |
var username; | |
websocket.on('connect', function(resource) | |
{ | |
clients.push(websocket); | |
websocket.write('Welcome to this chat server!'); | |
websocket.write('Please input your username:'); | |
websocket.write('Please input your username:'); | |
}); | |
websocket.on('data', function(data) | |
{ | |
if (!username) | |
{ | |
username = data.toString(); | |
websocket.write('Welcome, ' + username + '!'); | |
return; | |
} | |
var feedback = username + ' said: ' + data.toString(); | |
clients.forEach(function(client) | |
{ | |
client.write(feedback); | |
}); | |
}); | |
websocket.on('close', function() | |
{ | |
var pos = clients.indexOf(websocket); | |
if (pos >= 0) | |
{ | |
clients.splice(pos, 1); | |
} | |
}); | |
}).listen(8080); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment