Named pipes for client server implementation-How will server distinguish between two request from the same client

805 Views Asked by At

I have tried to implement client server model using named pipe. Now when client sends only one message to server the server is able to identify what was the message sent and prints it out. Now if client sends multiple message to same server, the server is not able to distinguish between the messages and prints out the both the client messages together instead of separately printing out both message. This is the code I am using:

  Server.c:
    int main(void)
    {
         FILE *fp;
        char readbuf[80];

  /*Create the FIFO if it does not exist */
  umask(0);
  mknod(FIFO_FILE, S_IFIFO|0777, 0);
  while(1)
  {
   fp=fopen(FIFO_FILE, "r");
   fgets(readbuf,80, fp);
   fprintf(stderr,"Received string: %s\n", readbuf);
   fclose(fp);
   fprintf(stderr,"Finished iteration\n");
  }

 return(0);
 }

   Client.c:
     int main()
     {
       FILE *fp;
        char * message1="message1";
        char * message2="message2";
         if((fp = fopen(FIFO_FILE, "w+")) == NULL) {
                perror("fopen");
                     exit(1);
      }

  fprintf(stderr,"Trying to transfer the first message\n");
  fputs(message1, fp);
  fprintf(stderr,"Transferred the first message\n");
  fprintf(stderr,"Trying to transfer the second message\n");
  fputs(message2, fp);
  fprintf(stderr,"Trying to transfer the second message\n");
  fclose(fp);
  return(0);
   }

Now, I know in the server end I am trying to read 80 bytes at a time which makes it to read all the characters together but whenever I am trying to read 5 bytes at a time in the server end it goes into infinite loop. There must be something wrong in my concept. I have one doubt can when I am modifying the server side to read 5 bytes at a time.It goes into infinite loop why does not it block after it has read all the messages that has been sent by client.

1

There are 1 best solutions below

0
Maxim Egorushkin On

There is no knowledge at pipe/stream level about what constitutes an application protocol message. There are, however, two most common ways to delimit messages in a stream:

  • prefix messages with their size and read that many bytes, or
  • read till a certain sequence of bytes is found (often \n (new-line symbol) for text-based protocols).

Use one of these methods to delimit messages in your stream.