基於TCP傳輸層的net模塊的小型服務器。

tcp層是http層的底層,更方便拿到請求者的響應頭信息。html

響應頭書寫換行的時候, 注意本身的操做系統是什麼。linux

  • windows下的換行是\r\n
  • linux下的換行是\n
  • mac下的換行是\r

服務器的config文件 server.confweb

port=8888
path=/web
path_position=relative
複製代碼

配置文件的處理文件 config.jswindows

const fs = require('fs');
const globalConfig = {}
const conf = fs.readFileSync('./server.conf', { encoding: "utf-8" });

const confs = conf.split('\r\n');
for (var i = 0; i < confs.length; i++) {
    var tempConf = confs[i].split('=');
    if (tempConf.length < 2) {
        continue;
    } else {
        globalConfig[tempConf[0]] = tempConf[1]
    }
}
if (globalConfig.path_position == 'relative') {
    globalConfig.basePath = __dirname + globalConfig.path
} else {
    globalConfig.basePath = globalConfig.path
}
console.log(globalConfig);
module.exports = globalConfig;
複製代碼

服務器文件 server.jsbash

const net = require('net');
const fs = require('fs');
const globalConfig = require('./config');
const url = require('url');

const server = net.createServer();

server.on('listening', () => {
    console.log('服務器已啓動')
})

server.on('connection', (socket) => {
    socket.on('data', (data) => {
        var requestUrl = data.toString().split("\r\n")[0].split(' ')[1];
        try {
            var dataFile = fs.readFileSync(globalConfig.basePath + requestUrl);
            socket.write(`HTTP 200OK\r\n\r\n`);
            socket.write(dataFile)
        } catch{
            socket.write(`HTTP 200OK\r\n\r\n<html><body>404</body></html>`)
        }
        socket.end()
    })
})

server.listen(globalConfig.port, '127.0.0.1');
複製代碼
相關文章
相關標籤/搜索