Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can node.js listen on UNIX socket?

Tags:

node.js

Can node.js listen on UNIX socket? I did not find any documentation regarding this. I only saw the possibility of listening on a dedicated port.

like image 358
Luc Avatar asked Aug 12 '11 19:08

Luc


People also ask

What port does node js listen on?

The default port for HTTP is 80 – Generally, most web browsers listen to the default port. Below is the code implementation for creating a server in node and making it listen to port 80.

Are UNIX sockets blocking?

The traditional UNIX system calls are blocking. For example: accept() blocks the caller until a connection is present. If no messages space is available at the socket to hold the message to be transmitted, then send() normally blocks.

Are UNIX sockets faster than TCP?

Unix domain sockets are often twice as fast as a TCP socket when both peers are on the same host. The Unix domain protocols are not an actual protocol suite, but a way of performing client/server communication on a single host using the same API that is used for clients and servers on different hosts.


2 Answers

To listen for incoming connections in node.js you want to use the net.server class.

The standard way of creating an instance of this class is with the net.createServer(...) function. Once you have an instance of this class you use the server.listen(...) function to tell the server where to actually listen.

If the first argument to listen is a number then nodejs will listen on a TCP/IP socket with that port number. However, if the first argument to listen is a string, then the server object will listen on a Unix socket at that path.

var net = require('net');  // This server listens on a Unix socket at /var/run/mysocket var unixServer = net.createServer(function(client) {     // Do something with the client connection }); unixServer.listen('/var/run/mysocket');  // This server listens on TCP/IP port 1234 var tcpServer = net.createServer(function(client) {     // Do something with the client connection }); tcpServer.listen(1234); 
like image 141
joshperry Avatar answered Sep 22 '22 12:09

joshperry


Yes. It's in the documentation.

https://nodejs.org/api/net.html#net_server_listen_path_backlog_callback

like image 31
Dan Grossman Avatar answered Sep 23 '22 12:09

Dan Grossman