hello
hello

Reputation: 19

Two way socket communication

I'm trying to write a simple two way socket communication using C. So far, the main while loop for my client.c file looks like this:

while ( gets(str) != NULL ) {
sSize = send(s, str, strlen(str), 0);
if ( len != strlen(str) ) {
  exit(1);
}

else {
   rSize  =  recv(s, buffer, 64, 0);
   buf[rSize] = '\0';
   printf("%s\n", buffer);
 }
}

while loop in sever.c looks like this:

while ( 1 ) {
gets(str);
send(p, str, strlen(str), 0);

  rSize = recv(p, buffer, 32, 0);   
  if ( rSize < 0 ) {
    exit(1);
  }
 buf[len] = '\0';
  else{
    printf("%s\n", buffer);
  }
}

The program compiles normally and I can establish connection between both machines, but when I send message either from client or server, I get an anomaly:

Sending message 'hi' from client

client -------------------------- server
hi                           

If I go to server to send 'you' message, I get:

client -------------------------- server
hi                           
                                  you
you                               hi

Not sure exactly how this is, but what I'm trying to achieve is that, whenever message is sent from either client or server, it should display immediately on the other side.

Upvotes: 1

Views: 804

Answers (1)

Arun Kaushal
Arun Kaushal

Reputation: 631

Please note that gets() is a blocking function. Initially both client and server are blocked in gets() waiting for input. When you type 'hi' on client, it sends this to the server which is still blocked on gets.

After sending hi, the client blocks on recv() call, waiting for message from server. On the other side, server hasn't still received the 'hi' message send by the client.

When you type 'you' on the server, it comes out of gets() and sends 'you' to client. After that the server calls recv() and reads the 'hi' sent by the client. Since the client is already waiting in recv(), it reads 'you' sent by the server.

Thus the program is working absolutely the way it has been implemented. Please mention your object, not sure what do you want to achieve.

Upvotes: 1

Related Questions