Skip to content

Instantly share code, notes, and snippets.

@dileephell
Created October 18, 2012 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dileephell/3910325 to your computer and use it in GitHub Desktop.
Save dileephell/3910325 to your computer and use it in GitHub Desktop.
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