Question

Hi I have problem with network programming. Is it possible to Receive particular message using recv() and ignore other message that also being send at same time IS it possible. assume that the server and client is already connected.

server.c

sprintf(client_message, "%s hello this is test message 1", packages.userName);
      write(connfd , client_message , strlen(client_message));  //Send the message back to client

   sprintf(client_message, "%s hello this is test message 2", packages.userName);
      write(connfd , client_message , strlen(client_message));  //Send the message back to client

   sprintf(client_message, "%s hello this is test message 3", packages.userName);
      write(connfd , client_message , strlen(client_message));  //Send the message back to client

client.c (But I want to receive only second message)

char server_reply[2000];
      int received_bytes = 0;
      int remaining_bytes = sizeof(server_reply);

      while (remaining_bytes > 0) {
          int res = recv(sockfd , &server_reply[remaining_bytes] , remaining_bytes, 0);
          if (res < 0) {
              printf("Connection lost from server...\n");
              isconnected = 0;
              close(sockfd);
              break;
          }
          received_bytes += res;
          remaining_bytes -= res;
      }

      puts(server_reply);

can anyone help please Thank you

Was it helpful?

Solution

No, a TCP socket is a stream of bytes: the bytes will be received in the order they are sent.

There are ways of achieving what you want.

If the sender and the receiver are both in the same machine, then you can use IPC:Message Queues (#include <sys/msg.h>) that supports message types/priorites.

You can also create a wrapper that reads all messages that have been received and then returns the message with the highest priority. (Note that this doesn't guarantee that message 2 will be processed before message 1, it only guarantees that message 2 will be processed before message 1 if it arrives before message 1 has been processed.)

Regardless, one thing that you need is a protocol. Right now, the receiver has no idea where one message ends and the next message starts. Remember that the notion of IP packages doesn't exist at the TCP level; the socket delivers a stream of bytes.

There is a mechanism in sockets called Out-of-Band data (OOB) that allows the transfer of data beside the normal stream. I've never used it myself, but I'm sure you can find examples on the internet.

OTHER TIPS

No, recv() by itself cannot do any sort of filtering, that's for the application to implement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top