| | |
Help with socket programming
Please support our C advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Nov 2007
Posts: 22
Reputation:
Solved Threads: 0
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:
Why did he use a while loop for this? Wouldn't you recieve the same data by just using
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
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:
Will there be any problems if I send the message over like this:
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:
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:
C Syntax (Toggle Plain Text)
while (totalBytesRcvd < echoStringLen) { /* Receive up to the buffer size (minus 1 to leave space for a null terminator) bytes from the sender */ if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0) DieWithError("recv() failed or connection closed prematurely"); totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */ echoBuffer[bytesRcvd] = '\0'; /* Terminate the string! */ printf("%s", echoBuffer); /* Print the echo buffer */ }
Why did he use a while loop for this? Wouldn't you recieve the same data by just using
C Syntax (Toggle Plain Text)
if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0) 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
C Syntax (Toggle Plain Text)
if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0) DieWithError("recv() failed or connection closed prematurely");
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:
C Syntax (Toggle Plain Text)
char message[50] = "Not enough to be 50"; char *msg = message;
Will there be any problems if I send the message over like this:
C Syntax (Toggle Plain Text)
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:
C Syntax (Toggle Plain Text)
#include <stdio.h> /* for printf() and fprintf() */ #include <sys/socket.h> /* for socket(), connect(), send(), and recv() */ #include <arpa/inet.h> /* for sockaddr_in and inet_addr() */ #include <stdlib.h> /* for atoi() and exit() */ #include <string.h> /* for memset() */ #include <unistd.h> /* for close() */ #define RCVBUFSIZE 32 /* Size of receive buffer */ void DieWithError(char *errorMessage); /* Error handling function */ int main(int argc, char *argv[]) { int sock; /* Socket descriptor */ struct sockaddr_in echoServAddr; /* Echo server address */ unsigned short echoServPort; /* Echo server port */ char *servIP; /* Server IP address (dotted quad) */ char *echoString; /* String to send to echo server */ char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */ unsigned int echoStringLen; /* Length of string to echo */ int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv() and total bytes read */ if ((argc < 3) || (argc > 4)) /* Test for correct number of arguments */ { fprintf(stderr, "Usage: %s <Server IP> <Echo Word> [<Echo Port>]\n", argv[0]); exit(1); } servIP = argv[1]; /* First arg: server IP address (dotted quad) */ echoString = argv[2]; /* Second arg: string to echo */ if (argc == 4) echoServPort = atoi(argv[3]); /* Use given port, if any */ else echoServPort = 7; /* 7 is the well-known port for the echo service */ /* Create a reliable, stream socket using TCP */ if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("socket() failed"); /* Construct the server address structure */ memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */ echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */ echoServAddr.sin_port = htons(echoServPort); /* Server port */ /* Establish the connection to the echo server */ if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) DieWithError("connect() failed"); echoStringLen = strlen(echoString); /* Determine input length */ /* Send the string to the server */ if (send(sock, echoString, echoStringLen, 0) != echoStringLen) DieWithError("send() sent a different number of bytes than expected"); /* Receive the same string back from the server */ totalBytesRcvd = 0; printf("Received: "); /* Setup to print the echoed string */ while (totalBytesRcvd < echoStringLen) { /* Receive up to the buffer size (minus 1 to leave space for a null terminator) bytes from the sender */ if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0) DieWithError("recv() failed or connection closed prematurely"); totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */ echoBuffer[bytesRcvd] = '\0'; /* Terminate the string! */ printf("%s", echoBuffer); /* Print the echo buffer */ } printf("\n"); /* Print a final linefeed */ close(sock); exit(0); }
Last edited by pocku; Oct 15th, 2009 at 8:44 pm.
•
•
Join Date: Sep 2008
Posts: 1,629
Reputation:
Solved Threads: 206
0
#2 Oct 15th, 2009
•
•
•
•
And the thing I don't really get is here in TCPEchoClient.c:
C Syntax (Toggle Plain Text)
while (totalBytesRcvd < echoStringLen) { /* Receive up to the buffer size (minus 1 to leave space for a null terminator) bytes from the sender */ if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0) DieWithError("recv() failed or connection closed prematurely"); totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */ echoBuffer[bytesRcvd] = '\0'; /* Terminate the string! */ printf("%s", echoBuffer); /* Print the echo buffer */ }
Why did he use a while loop for this? Wouldn't you recieve the same data by just using
C Syntax (Toggle Plain Text)
if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0) 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]
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.
Out.
•
•
Join Date: Nov 2007
Posts: 22
Reputation:
Solved Threads: 0
0
#3 Oct 15th, 2009
•
•
•
•
...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.
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?
0
#4 Oct 16th, 2009
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
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
![]() |
Similar Threads
- Socket Programming... (C#)
- About socket programming in php (PHP)
- Socket Programming (C++)
- Eclipse SDK/Socket Programming help (Java)
- Socket Programming (ASP.NET)
- C++ socket programming (C++)
- Socket programming + porting Unix to Win32 (C)
Other Threads in the C Forum
- Previous Thread: xor hexa arrays in ansi c
- Next Thread: how can I output 123454321, if I input 5.?
| Thread Tools | Search this Thread |
Tag cloud for C
adobe ansi api array arrays asterisks binarysearch calculate centimeter char command convert copyimagefile copypdffile cprogramme creafecopyofanytypeoffileinc createcopyoffile csyntax directory drawing dynamic executable fflush file fork forloop frequency getlasterror givemetehcodez graphics gtkgcurlcompiling hacking hardware highest homework i/o inches incrementoperators infiniteloop kernel km lazy linked linkedlist linux linuxsegmentationfault list lists locate logical_drives match matrix microsoft motherboard multi mysql number open opendocumentformat opensource owf pattern pdf performance pointer pointers posix problem probleminc program programming radix recursion recv repetition research scanf scheduling scripting segmentationfault send sequential shape socketprograming spoonfeeding stack standard string strings structures student systemcall testautomation turboc unix user variable voidmain() wab windows.h






