栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用node

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用node

最后,我将其与下面的代码一起使用。您可以免费获得它!

服务器

#include <stdio.h>#include <unistd.h>#include <sys/socket.h>#include <sys/un.h>#include <stdlib.h>char *socket_path = "/tmp/icp-test";int main(int argc, char *argv[]) {  struct sockaddr_un addr;  char buf[100];  int fd,cl,rc;  if (argc > 1) socket_path=argv[1];  if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {    perror("socket error");    exit(-1);  }  memset(&addr, 0, sizeof(addr));  addr.sun_family = AF_UNIX;  if (*socket_path == '') {    *addr.sun_path = '';    strncpy(addr.sun_path+1, socket_path+1, sizeof(addr.sun_path)-2);  } else {    strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path)-1);    unlink(socket_path);  }  if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {    perror("bind error");    exit(-1);  }  if (listen(fd, 5) == -1) {    perror("listen error");    exit(-1);  }  while (1) {    if ( (cl = accept(fd, NULL, NULL)) == -1) {      perror("accept error");      continue;    }    while ( (rc=read(cl,buf,sizeof(buf))) > 0) {      printf("read %u bytes: %.*sn", rc, rc, buf);    }    if (rc == -1) {      perror("read");      exit(-1);    }    else if (rc == 0) {      printf("EOFn");      close(cl);    }  }  return 0;}

client.js:

 var ipc=require('node-ipc');var socketId = 'icp-test';ipc.config.id   = 'hello';ipc.config.socketRoot = '/tmp/';ipc.config.appspace = '';ipc.config.retry= 1500;ipc.connectTo(  socketId,  function(){    ipc.of[socketId].on(      'connect',      function(){        console.log("Connected!!");        ipc.log('## connected to world ##'.rainbow, ipc.config.delay);        ipc.of[socketId].emit(          'message',  //any event or message type your server listens for          'hello'        )      }    );    ipc.of[socketId].on(      'disconnect',      function(){        console.log("Disconnected!!");        ipc.log('disconnected from world'.notice);      }    );    ipc.of[socketId].on(      'message',  //any event or message type your server listens for      function(data){        console.log("Got a message!!");        ipc.log('got a message from world : '.debug, data);      }    );  });

附带说明一下,我已经意识到,如果您只想通过带有C的unix套接字在NodeJS之间进行通信,则NodeJS实际上已经带有一个已经完成该任务的模块。事实证明,这是

node-ipc
引擎盖下使用的东西。因此,仅使用NodeJS的
net
包可能会更容易。前面的问题指出了如何在NodeJS中执行IPC。只需将其与上面的C代码结合即可。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/375438.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号