I am using C language and Linux as platform to develop two small applications. The first one, a client, sends a character via socket and the second, a server, reads the message and sends back the same thing that was read.
Once there's a connection established between the applications then the following code is supposed to send and receive the same message 5 times:
code edited:
char buf[100];
char message[100];
fd_set readfds, writefds;
int n, rvd;
memset(message, 0, sizeof(message));
message[0] = 'a';
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
printf("client: connecting to,, %s\n", s);
freeaddrinfo(servinfo);
n = sockfd+1;
for (unsigned long i=0; i<5; i++)
{
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_SET(sockfd, &readfds);
FD_SET(sockfd, &writefds);
rvd = select(n, NULL, &writefds, NULL, NULL);
if (rvd > 0)
{
printf("client: writing '%s'\n",message);
if ((numSent = send(sockfd, message, strlen(message), 0)) != -1)
{
rvd = select(n, &readfds, NULL, NULL, NULL);
if (rvd > 0)
{
if ((numbytes = recv(sockfd, buf, numSent, 0)) != -1)
{
printf("client: received '%s'\n",buf);
}
//timestamp it
//count successful package sent
}
else
{
//throw this measurement
}
}
}
}
The program sends and receives messages successfully twice. When it attempts to send for the thirds time it fails, even though the function select returns a value bigger than 0 (which means that the server is ready to receive data).
When debugging with eclipse the function send() crashes on its third execution and the following message is shown:
No source available for "send() at 0x7ffff7bcc282"
View Disassembly... [button]
When I run the server application on a virtual machine everything runs OK though.
Any thoughts? Thanks in advance!
There are two problems with your code:
you are not resetting readfds and writefds every time you call select(), as it modifies them each time.
you are misusing sizeof().
Try something more like this instead:
char message[1024];
char buf[1024];
fd_set readfds, writefds;
int numSent, numRead;
memset(message, 0, sizeof(message));
strncpy(message, "whatever you need to send...", sizeof(message)-1);
for (unsigned long i = 0; i < 5; ++i)
{
FD_ZERO(&writefds);
FD_SET(sockfd, &writefds);
FD_ZERO(&readfds);
FD_SET(sockfd, &readfds);
rvd = select(sockfd+1, NULL, &writefds, NULL, NULL);
if (rvd == -1)
break;
printf("client: writing '%s'\n", message);
if ((numSent = send(sockfd, message, strlen(message), 0)) < 1)
break;
rvd = select(sockfd+1, &readfds, NULL, NULL, NULL);
if (rvd == -1)
break;
if ((numRead = recv(sockfd, buf, numSent, 0)) < 1)
break;
printf("client: received '%*s'\n", numRead, buf);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With