我最終用下面的代碼來完成它。你可以免費獲得它!
server.c
#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 == '\0') {
*addr.sun_path = '\0';
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: %.*s\n", rc, rc, buf);
}
if (rc == -1) {
perror("read");
exit(-1);
}
else if (rc == 0) {
printf("EOF\n");
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);
}
);
}
);
在一個側面說明,我已經意識到,如果你只想做之間的NodeJS溝通通過與C的unix套接字,NodeJS實際上帶有a module that does that already。事實證明,這是node-ipc
在引擎蓋下使用。因此,使用NodeJS的net
包可能會更容易。 This previous question points out how to do IPC in NodeJS.只需將它與上面的C代碼結合起來即可。
您是否試圖在兩個方向上交流程序?這是一個商業項目嗎?你會支付幫助嗎? –
是的,兩個方向。支付幫助並不是一個真正的選擇,我只需要向正確的方向推動。我打算使用ZeroMQ,但它似乎總是過度殺傷 – Jodes
如果它在POSIX系統上,實際上這是一個非常簡單的任務。可悲的是,我不能幫你免費,或者在這裏回答,因爲我認爲你需要的不僅僅是簡單的幫助。 Unix域套接字是要走的路,我相信,如果你google的權利,你會發現很多與C代碼包括的例子。事實上,這是一個非常簡單的事情,就像一個普通的套接字,但是地址和類型不同。 –