首页 文章

用于TCP类型服务器的Unix域套接字而不是主机/端口

提问于
浏览
0

这适用于所有Node.js版本6

假设我目前有一个包含多个客户端的TCP服务器:

const server = net.createServer(s => {

});

server.listen(6000);

我与客户连接:

const s1  = net.createConnection({port:6000});
const s2  = net.createConnection({port:6000});
const s3  = net.createConnection({port:6000});

TCP在本地计算机上有时会有点慢 . 我听说可能有办法用Unix域套接字替换主机/端口组合,但维护TCP服务器样式接口 . 这可能吗?怎么样?

Node.js文档提到你可以创建一个侦听路径的服务器:https://nodejs.org/api/net.html#net_server_listen_path_backlog_callback

但它没有指定需要的文件类型以及如何创建该文件 .

1 回答

  • 0

    事实证明在MacOS / Linux上这很容易 . 您不需要创建该文件 . 您需要确保该文件不存在,然后将Node.js核心库指向空路径 .

    对于服务器:

    const udsPath = path.resolve('some-path.sock');
    
    const wss = net.createServer(s => {
    
    });
    
    wss.listen(udsPath, () => {
    
    
    });
    

    对于客户:

    const udsPath = path.resolve('some-path.sock'); // same file path as above
    
    const ws = net.createConnection(udsPath, () => {
    });
    

相关问题