Nodejs学びながらtelnetチャットツール

2544 ワード

  Net module         ,    telnet       
var net = require('net');
var config = {
	separate : '\r
' }; var connections = new Object(); var server = net.createServer(function (c) { var ip = c.remoteAddress; var port = c.remotePort; connections[ip+port] = c; c.write('Welcome to chat room! your ip is ' + ip+port); c.write(config.separate + 'I say:'); var buffers = []; c.setEncoding('utf-8'); c.on('data', function (data) { var index = data.indexOf(config.separate); if (index < 0) { buffers.push(data); } else { var contents = data.split(config.separate); // contents[0] + buffers will send var buffer = ''; for (var i = 0, l = buffers.length; i < l; i++) { buffer += buffers[i]; } var message = contents[0] + buffer; buffers = []; sendAll(c, message); // contents[n] will send if (contents.length > 2) { for (var i = 1, l = contents.length; i < l - 1; i++) { sendAll(c, contents[i]); } } // contents[last] will be push into buffers buffers.push(new Buffer(contents[contents.length - 1])); } }); c.on('close',function(){ delete connections[ip+port]; }); }); function sendAll(conn, message) { for (var address in connections) { if(connections.hasOwnProperty(address)){ console.log(address); if (conn != connections[address]) { console.log('other'); var what2say = config.separate + conn.remoteAddress + ':' + conn.remotePort + '@[' + now() + '] said:' + message + config.separate + 'I say: '; connections[address].write(what2say); } else { console.log('self'); connections[address].write(config.separate + 'I say: '); } } } } function now() { var date = new Date(); hour = date.getHours(); min = date.getMinutes(); sec = date.getSeconds(); return hour + ':' + min + ':' + sec; } server.listen(8888, function () { console.log('listen to 8888....'); });

先周末にまた1つのホームページ版を作って、すぐにアップロードします.