基于unix socket的HTTP Server

基于 Unix Socket 协议的 HTTP Server

同时相比较 TCP 协议实现的可靠传输,Unix Socket 作为 IPC 有些优点:

  • Unix Socket 仅仅复制数据,并不执行协议处理,不需要添加或删除网络报头,无需计算校验和,不产生顺序号,也不需要发送确认报文
  • 仅依赖命名管道,不占用端口

Unix Socket 并不是一种协议,它是进程间通信(IPC)的一种方式,解决本机的两个进程通信

server 端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const http = require("http");
const path = require("path");
const fs = require("fs");

const myServer = http.createServer(function (req, res) {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello World\n");
});

myServer.on("error", (e) => {
// 当sock文件被占用的时候删除文件
if (e.code === "EADDRINUSE") {
fs.unlinkSync(e.address);
myServer.listen(path.join(process.cwd(), "myctl.sock"));
}
});

// 防止进程退出后sock文件仍然被占用
process.on("SIGINT", function () {
myServer.close();
console.log("\nSIGINT, server closed");
process.exit();
});

myServer.listen(path.join(process.cwd(), "myctl.sock"));
console.log("Server running at " + path.join(process.cwd(), "myctl.sock"));

client 端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var http = require("http");
var path = require("path");

var options = {
socketPath: path.join(process.cwd(), "myctl.sock"),
method: "GET",
path: "",
};

var req = http.request(options, function (res) {
console.log("STATUS: " + res.statusCode);
console.log("HEADERS: " + JSON.stringify(res.headers));

res.on("data", function (chunk) {
console.log(chunk.toString());
});
});

req.end();