var net = require('net');
var port = process.argv[2];
var getTime = function () {
var date = new Date();
year = date.getFullYear();
month = formate(date.getMonth() + 1);
day = formate(date.getDate());
hour = formate(date.getHours());
minute = formate(date.getMinutes());
var time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
function formate(time) {
return (time.toString().length > 1 ? '' : '0' ) + time;
}
console.log(time);
return time;
};
var server = net.createServer(function(socket){
socket.write(getTime() + '\n');
socket.end();
}).listen(port);
HTTP是应用层协议,TCP是传输层协议,可以粗暴地理解为:(并不严谨)
上面
net.createServer()
创建的并不是HTTP服务器,因此无法在浏览器里访问,正确的做法如下,更多内容可以参考之前写的总结《Nodejs进阶:核心模块net入门与实例讲解》