在Node.js中打开多个UNIX域套接字:为什么我得到EAGAIN错误?

我的用例(webservice):

多个客户端=> Webserver =>通过UNIX域套接字向C程序发送消息。

我一直在使用Apache + PHP的Web服务器层,但我目前正在用Node.jsreplace它的过程。

web服务最多可以达到100个请求/秒,所以当一个新的请求进来时,C程序会很忙,这是一个非常真实的情况.PHP处理得很好,但是Node.js通常会失败,

{ "code": "EAGAIN", "errno": "EAGAIN", "syscall": "connect", "address": "/tmp/service.sock" } 

我假设这是因为PHP执行某种消息队列/重试,将确保所有消息发送到C程序(哪个Node.js不)。

有没有一种简单的方法来做同样的Node.js或将不得不实现一个自定义的消息队列?

C套接字创build:

 int listenSocket, newSocket; struct sockaddr_un localAddress, remoteAddress; // Create socket if ((listenSocket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1){ printf("Error opening listener socket"); exit(1); } // Configure socket localAddress.sun_family = AF_UNIX; // Set UNIX domain socket type strcpy(localAddress.sun_path, "/tmp/service.sock"); unlink(localAddress.sun_path); // Remove any previous instances of the socket // Open listener socket int len = strlen(localAddress.sun_path) + sizeof(localAddress.sun_family); if (bind(listenSocket, (struct sockaddr *)&localAddress, len) == -1){ printf("Error binding socket at %s", localAddress.sun_path); exit(1); } chmod(localAddress.sun_path, 0777); // Listen for new connections on the listener socket if (listen(listenSocket, 5) == -1){ printf("Error listening on listener socket"); exit(1); } // Handle new connections while(!shutdown){ printf("Waiting for a connection...\n"); // Accept new connection int sizeofRemoteAddress = sizeof(remoteAddress); if ((newSocket = accept(listenSocket, (struct sockaddr *)&remoteAddress, &sizeofRemoteAddress)) == -1){ printf("Error accepting new connection: %s\n", strerror(errno)); continue; } // Read and handle data from client... } 

在PHP中连接到套接字:

 $socket = @socket_create(AF_UNIX, SOCK_STREAM, 0); if (!$socket) return false; $connected = @socket_connect($socket, "/tmp/service.sock"); if (!$connected) return false; // Send message to server and read response... 

连接到Node.js中的套接字:

 new Promise(function(resolve, reject){ var socket = Net.connect("/tmp/service.sock"); socket.on("error", function(err){ reject(err); }); socket.on("connect", function(){ socket.write(message); }); socket.on("data", function(data){ socket.end(); resolve(data.toString("UTF-8")); }); }); 

EAGAIN是系统调用中断时的预期条件。 您应该在获得EAGAIN错误代码时重复相同的调用。 在典型的C程序中,你会看到很多while (returnCode == -1 && errno == EAGAIN)循环风格。 如果你期望有许多中断,你可以先禁用中断(不知道在node.js中是如何完成的),进行系统调用,然后再次启用中断。 不知道这个答案对于node.js应用程序是否node.js但是我还是认为我提到了它。