node.js 可以监听 UNIX 套接字吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7045614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can node.js listen on UNIX socket?
提问by Luc
Can node.jslisten on UNIX socket? I did not find any documentation regarding this. I only saw the possibility of listening on a dedicated port.
可以node.js监听 UNIX 套接字吗?我没有找到任何关于此的文档。我只看到了在专用端口上侦听的可能性。
采纳答案by Dan Grossman
Yes. It's in the documentation.
是的。它在文档中。
https://nodejs.org/api/net.html#net_server_listen_path_backlog_callback
https://nodejs.org/api/net.html#net_server_listen_path_backlog_callback
回答by joshperry
To listen for incoming connections in node.js you want to use the net.serverclass.
要侦听 node.js 中的传入连接,您需要使用net.server类。
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.
创建此类实例的标准方法是使用net.createServer(...)函数。一旦你有了这个类的实例,你就可以使用该server.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.
如果侦听的第一个参数是一个数字,则 nodejs 将侦听具有该端口号的 TCP/IP 套接字。然而,如果监听的第一个参数是一个字符串,那么服务器对象将监听该路径上的 Unix 套接字。
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);

