A TCP service written by NodeJS can listen on a sock file (Domain Socket), and its HTTP service can do the same. Although it doesn't make much sense to connect to a sock file as an HTTP service, it's just a pure attempt here.
This is how the TCP service is written
The code copy is as follows:
var net = require('net');
net.createServer(function (socket) {
socket.on('data', function (data) {
socket.write('received: ' + data);
});
}).listen('/tmp/node_tcp.sock');
Connect the above '/tmp/node_tcp.sock'
The code copy is as follows:
telnet /tmp/node_tcp.sock
Trying /tmp/node_tcp.sock...
Connected to (null).
Escape character is '^]'.
Hello World!
received: Hello World!
To be precise, this article should be NodeJS's TCP and HTTP listening for Domain Socket files.
It is still very common for TCP listening to Domain Sockets. For example, sometimes accessing the native database or cache will be done, such as using '/tmp/mysql.sock' to access the native MySQL service, so that there is no need to start the TCP port to be exposed, and security is improved and performance is also improved.
Now let’s take a look at NodeJS’ HTTP listening on Domain Socket, and transform it from classic examples.
The code copy is as follows:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World/n');
}).listen('/tmp/node_http.sock');
console.log('Server running at /tmp/node_http.sock');
I don't know how to access the above HTTP service in the browser, so I use telnet to test it
The code copy is as follows:
telnet /tmp/node_http.sock
Trying /tmp/node_http.sock...
Connected to (null).
Escape character is '^]'.
GET / HTTP/1.1
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Mon, 26 Jan 2015 04:21:09 GMT
Connection: keep-alive
Transfer-Encoding: chunked
c
Hello World
0
Can correctly handle HTTP requests on '/tmp/node_http.sock'.
Use NodeJS HTTP Client to access
The code copy is as follows:
var http = require('http');
var options = {
socketPath: '/tmp/node_http.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();
Execute the above code, if the file name is http_client.js,
The code copy is as follows:
node http_client.js
STATUS: 200
HEADERS: {"content-type":"text/plain","date":"Mon, 26 Jan 2015 04:25:49 GMT","connection":"close","transfer-encoding":"chunked"}
Hello World
This article is only for record, and I can't imagine the actual purpose of letting the HTTP service listen on the Domain Socket, and the browser cannot access it.