1

Client side code

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);
    }
}

Server Side Code

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();
    });

});

I'm able to send msg from client to server but I'm having trouble to send the msg from server to client. I need a 2-way communication between client and server. Can someone help me how to achieve that from the server side.

I looked for the answer on this link but it was not helpful.

Ghost
  • 21
  • 1
  • 7

0 Answers0