zhiFEclub / nodejs-learn

学习 Node.js
1 stars 0 forks source link

任务10-授时服务器 #10

Open iamjoel opened 7 years ago

iamjoel commented 7 years ago
var net = require('net')
var port = process.argv[2]

var server = net.createServer(function(socket) {
  socket.write(getCurrentTimeStr())
  socket.write('\n')
  socket.end()
})
server.listen(port)

function getCurrentTimeStr() {
  var now = new Date()
  var year = now.getFullYear()
  var month = fillZero(now.getMonth() + 1)
  var date = fillZero(now.getDate())
  var hour = fillZero(now.getHours())
  var minute = fillZero(now.getMinutes())
  return [year, month, date].join('-') + ' ' + [hour, minute].join(':')
}

function fillZero(value) {
  return value < 10 ? ('0' + value) : value
}
wmh1106 commented 7 years ago
'use strict';
let net = require('net');
// 参数:(被你坑惨了)记住,请一定监听由第一个命令行参数指定的端口。
let port = Number(process.argv[2]);

function zero(n) {
    return n > 9 ? '' + n : '0' + n;
}

function times() {
    let date = new Date();
    return `${date.getFullYear()}-${zero(date.getMonth()+1)}-${zero(date.getDate())} ${zero(date.getHours())}:${zero(date.getMinutes())}`;
}

let netServer = net.createServer(socket => {
    // 练习涉及:写 关闭
    // YYYY-MM-DD hh:mm" \n
    socket.write(times())
    socket.write('\n')
    socket.end()
})
netServer.listen(port);

没注意端口是参数,😌坑死人了

SShnoodles commented 7 years ago
let net = require('net');
let strftime = require('strftime');

let server = net.createServer(socket => socket.end(strftime('%F %R') + '\n')); 
server.listen(process.argv[2]);