Skip to content

Instantly share code, notes, and snippets.

@kanreisa
Created May 27, 2011 09:56
Show Gist options
  • Save kanreisa/994974 to your computer and use it in GitHub Desktop.
Save kanreisa/994974 to your computer and use it in GitHub Desktop.
node.js demo chat
/**
* node.js demo chat server (app.js)
**/
var http = require('http');
var io = require('socket.io');
var port = 13902;
var server = http.createServer(function(req, res){
res.writeHead(301, {
'Content-Type': 'text/html',
'Location': 'http://node.demo.r2.ag/chat/',
});
res.end('node.js demo chat server');
});
server.listen(port);
console.log('node.js/socket.io server listening on port %d', port);
var data = {
count : 0,
total : 0,
maxi : 0,
nick : 'node',
mess : 'hello world',
time : '00:00:00'
};
var socket = io.listen(server);
socket.on('connection', function(client){
data.count++;//接続数+1
data.total++;//累計+1
if(data.maxi < data.count) data.maxi = data.count;//最大値保存
client.broadcast(JSON.stringify(data));
client.send(JSON.stringify(data));
client.on('message', function(message){
var obj = JSON.parse(message);//送られてきたメッセージをパース
var d = new Date();//時間取得
data.nick = obj.nick;
data.mess = obj.mess;
data.time = zero(d.getHours(), 2) + ':' + zero(d.getMinutes(), 2) + ':' + zero(d.getSeconds(), 2);
client.broadcast(JSON.stringify(data));
client.send(JSON.stringify(data));
console.log('[message]' + data.time + '<' + data.nick + '>' + data.mess);
});
client.on('disconnect', function(){
data.count--;
client.broadcast(JSON.stringify(data));
});
console.log('[status]' + data.count + 'online/' + data.total + 'total/' + data.maxi + 'max');
});
//ぜろつけるやつ
var zero = function(pNumber, pDigit){
var num = '' + pNumber;
while(num.length < pDigit){
num = '0' + num;
}
return num;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment