如何使用Node.js处理UNIX域套接字连接?

时间:2015-04-24 11:12:02

标签: node.js sockets unix

我试图用一些C进程传递Node.js应用程序,我认为在UNIX套接字上按性能顺序排列,但是我对如何处理它感到有些困惑。

我试过了:

var net = require('net');
var fs = require('fs');
var path = '/tmp/echo.sock';
fs.unlink(path, function () {
  var server = net.createServer(function(c) {
    console.log('server connected');
    c.on('end', function() {
      console.log('server disconnected');
    });

    c.on('data', function (data) {
        console.log(data.toString());
    });

    c.on('error', function (err) {
        console.log(err);
    });
    c.write('hello\r\n');
    c.pipe(c);
  });
  server.listen(path, function() {
    console.log('server bound on %s', path);
  });
});

我用sudo运行它并且它正在监听,然后我创建了这个C客户端:

 #include <sys/types.h>
 #include <sys/socket.h>
 #include <sys/un.h>
 #include <stdio.h>
 #define DATA "Half a league, half a league . . ."
 main(argc, argv)
     int argc;
     char *argv[];
 {
     int sock;
     struct sockaddr_un server;
     char buf[1024];
     if (argc < 2) {
         printf("usage:%s <pathname>", argv[0]);
         exit(1);
     }
     sock = socket(AF_UNIX, SOCK_STREAM, 0);
     if (sock < 0) {
         perror("opening stream socket");
         exit(1);
     }
     server.sun_family = AF_UNIX;
     strcpy(server.sun_path, argv[1]);
     if (connect(sock, (struct sockaddr *) &server, sizeof(struct sockaddr_un)) < 0) {
         close(sock);
         perror("connecting stream socket");
         exit(1);
     }
     if (write(sock, DATA, sizeof(DATA)) < 0)
         perror("writing on stream socket");
     close(sock);
 }

但是每当我按sudo ./socket /tmp/echo.sock执行C程序时,就会出现节点错误:

{ [Error: write EPIPE] code: 'EPIPE', errno: 'EPIPE', syscall: 'write' }

我该如何实现?

0 个答案:

没有答案