客户端代码
int s, t, len;
struct sockaddr_un remote;
char str[100];
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
printf("Trying to connect...\n");
remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCK_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
if (connect(s, (struct sockaddr *)&remote, len) == -1) {
perror("connect");
exit(1);
}
printf("Connected.\n");
while(printf("Client > "), fgets(str, 100, stdin), !feof(stdin)) {
if (send(s, str, strlen(str), 0) == -1) {
perror("send");
exit(1);
}
if ((t=recv(s, str, 100, 0)) > 0) {
str[t] = '\0';
printf("%s", str);
} else {
if (t < 0) perror("recv");
else printf("Server closed connection\n");
exit(1);
}
}
服务器端代码
var server = net.createServer(function(c) {
console.log('server connected');
c.setEncoding('utf8');
c.on('end', function() {
console.log('server disconnected');
});
c.on('data',function(data){
console.log('Client >',data.replace(/\n|\r/g, ""));
c.write("Data Recived :- "+data);
});
// c.on('close',function(){
// console.log('connection closed');
// });
c.on('error',function(err){
c.end();
});
});
我能够将msg从客户端发送到服务器,但是我无法将msg从服务器发送到客户端。我需要客户端和服务器之间的双向通信。有人可以帮助我如何从服务器端实现这一目标。
我在this link上找到了答案,但没有帮助。