944,041 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 888
  • C RSS
Oct 15th, 2009
0

Help with socket programming

Expand Post »
I've just started started socket programming so there's a few things I'm wondering about:

I found a set of socket programming codes here:
http://cs.baylor.edu/~donahoo/practi.../textcode.html

And the thing I don't really get is here in TCPEchoClient.c:
  1. while (totalBytesRcvd < echoStringLen)
  2. {
  3. /* Receive up to the buffer size (minus 1 to leave space for
  4.   a null terminator) bytes from the sender */
  5. if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)
  6. DieWithError("recv() failed or connection closed prematurely");
  7. totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */
  8. echoBuffer[bytesRcvd] = '\0'; /* Terminate the string! */
  9. printf("%s", echoBuffer); /* Print the echo buffer */
  10. }

Why did he use a while loop for this? Wouldn't you recieve the same data by just using

  1. if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)
  2. DieWithError("recv() failed or connection closed prematurely");

In the project I'm doing, I don't really know how long the string I will be recieving is so can I/should I just write something like

  1. if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)
  2. DieWithError("recv() failed or connection closed prematurely");
without the while loop?

EDIT: I tried it out and yeah, I recieved the same message with or without the while loop so my question still stands, why use a while loop?

But more importantly... the thing I'm having trouble with in my project is...

Okay, say I have a message to send like this:

  1. char message[50] = "Not enough to be 50";
  2. char *msg = message;

Will there be any problems if I send the message over like this:
  1. send(int fd, msg, 50,int flags);

That is, can I send my message based on the length of the char array rather than the actual number of characters in the string?

The thing is, the length of my message differs depending on the situation. If it is an error message the length would be 51, if it is an acknowledgement message it would be length 10. Is there any way to send the message without using if clauses like:

if there's an error, send message of length 51
else send message of length 10

Also, if anyone needs to see the original TCPEchoClient.c code:

  1. #include <stdio.h> /* for printf() and fprintf() */
  2. #include <sys/socket.h> /* for socket(), connect(), send(), and recv() */
  3. #include <arpa/inet.h> /* for sockaddr_in and inet_addr() */
  4. #include <stdlib.h> /* for atoi() and exit() */
  5. #include <string.h> /* for memset() */
  6. #include <unistd.h> /* for close() */
  7.  
  8. #define RCVBUFSIZE 32 /* Size of receive buffer */
  9.  
  10. void DieWithError(char *errorMessage); /* Error handling function */
  11.  
  12. int main(int argc, char *argv[])
  13. {
  14. int sock; /* Socket descriptor */
  15. struct sockaddr_in echoServAddr; /* Echo server address */
  16. unsigned short echoServPort; /* Echo server port */
  17. char *servIP; /* Server IP address (dotted quad) */
  18. char *echoString; /* String to send to echo server */
  19. char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */
  20. unsigned int echoStringLen; /* Length of string to echo */
  21. int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv()
  22.   and total bytes read */
  23.  
  24. if ((argc < 3) || (argc > 4)) /* Test for correct number of arguments */
  25. {
  26. fprintf(stderr, "Usage: %s <Server IP> <Echo Word> [<Echo Port>]\n",
  27. argv[0]);
  28. exit(1);
  29. }
  30.  
  31. servIP = argv[1]; /* First arg: server IP address (dotted quad) */
  32. echoString = argv[2]; /* Second arg: string to echo */
  33.  
  34. if (argc == 4)
  35. echoServPort = atoi(argv[3]); /* Use given port, if any */
  36. else
  37. echoServPort = 7; /* 7 is the well-known port for the echo service */
  38.  
  39. /* Create a reliable, stream socket using TCP */
  40. if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
  41. DieWithError("socket() failed");
  42.  
  43. /* Construct the server address structure */
  44. memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */
  45. echoServAddr.sin_family = AF_INET; /* Internet address family */
  46. echoServAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */
  47. echoServAddr.sin_port = htons(echoServPort); /* Server port */
  48.  
  49. /* Establish the connection to the echo server */
  50. if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
  51. DieWithError("connect() failed");
  52.  
  53. echoStringLen = strlen(echoString); /* Determine input length */
  54.  
  55. /* Send the string to the server */
  56. if (send(sock, echoString, echoStringLen, 0) != echoStringLen)
  57. DieWithError("send() sent a different number of bytes than expected");
  58.  
  59. /* Receive the same string back from the server */
  60. totalBytesRcvd = 0;
  61. printf("Received: "); /* Setup to print the echoed string */
  62. while (totalBytesRcvd < echoStringLen)
  63. {
  64. /* Receive up to the buffer size (minus 1 to leave space for
  65.   a null terminator) bytes from the sender */
  66. if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)
  67. DieWithError("recv() failed or connection closed prematurely");
  68. totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */
  69. echoBuffer[bytesRcvd] = '\0'; /* Terminate the string! */
  70. printf("%s", echoBuffer); /* Print the echo buffer */
  71. }
  72.  
  73. printf("\n"); /* Print a final linefeed */
  74.  
  75. close(sock);
  76. exit(0);
  77. }
Last edited by pocku; Oct 15th, 2009 at 8:44 pm.
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
pocku is offline Offline
22 posts
since Nov 2007
Oct 15th, 2009
0
Re: Help with socket programming
Click to Expand / Collapse  Quote originally posted by pocku ...
And the thing I don't really get is here in TCPEchoClient.c:
  1. while (totalBytesRcvd < echoStringLen)
  2. {
  3. /* Receive up to the buffer size (minus 1 to leave space for
  4.   a null terminator) bytes from the sender */
  5. if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)
  6. DieWithError("recv() failed or connection closed prematurely");
  7. totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */
  8. echoBuffer[bytesRcvd] = '\0'; /* Terminate the string! */
  9. printf("%s", echoBuffer); /* Print the echo buffer */
  10. }

Why did he use a while loop for this? Wouldn't you recieve the same data by just using

  1. if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)
  2. DieWithError("recv() failed or connection closed prematurely");

In the project I'm doing, I don't really know how long the string I will be recieving is....

[/CODE]
To follow that with another question, if you remove the while statement, what happens if the amount of information you receive exceeds the buffer size? Even from the author's comments, it looks like it will successfully store up to the buffer size amount of bytes, but then, you would not read in the rest of the data. So I'm assuming that the reason for the while loop is to ensure that all of the data is read in - even if it exceeds the size of the buffer. But what do I know, I'm honestly surprised they even let me post in the C forum anymore.

Either way, good luck on your assignment. I have a similar project that I haven't started yet - setting up sockets in C with a client/server model is apparently somewhat difficult.
Last edited by BestJewSinceJC; Oct 15th, 2009 at 8:41 pm.
Reputation Points: 874
Solved Threads: 352
Posting Maven
BestJewSinceJC is offline Offline
2,758 posts
since Sep 2008
Oct 15th, 2009
0
Re: Help with socket programming
...So I'm assuming that the reason for the while loop is to ensure that all of the data is read in - even if it exceeds the size of the buffer. But what do I know, I'm honestly surprised they even let me post in the C forum anymore.


Either way, good luck on your assignment. I have a similar project that I haven't started yet - setting up sockets in C with a client/server model is apparently somewhat difficult.
Thanks! And yeah, I'm actually having quite a hard time getting this right....

Also, you're most likely right since I received a bunch of gibberish from time to time now without the while loop... so how am I going to receive data if I don't know the exact character length I will be receiving?
Reputation Points: 10
Solved Threads: 0
Newbie Poster
pocku is offline Offline
22 posts
since Nov 2007
Oct 16th, 2009
0
Re: Help with socket programming
my tack is
i have to send some command to tcp/ip reader ,then i have to get resopnse,next i have to send one more command to tcp/ip,and i should get response,but iam not able to get response,
for the first send command iam able to get response,after send command,iam not able to get,without closing the socket,i have to send and receive,and send and receive,like that i have to do,so please help me

pleae give some fast response
thanks
Reputation Points: 9
Solved Threads: 0
Light Poster
nandux8 is offline Offline
31 posts
since Sep 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: xor hexa arrays in ansi c
Next Thread in C Forum Timeline: whats wrong with this code





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC