Reputation: 331
I need to implement a server code that receives a length of the expression and is going to receive it from the client, and it should wait up to 500 milliseconds, as noted below:
"When the server receives the length message it will wait up to 500 milliseconds for that number of bytes to be sent."
The program consist of a simple UDP server-client program where the client sends an expression and the server processes it. I'm using sendto()
and recvfrom()
to send data between client/server respectively.
This code is supposed to run on unix machines. I saw a similar question that had the same problem, and it was solved, but not for me. I've changed the code to be more similar as the recvfrom() system call, however it still doesn't work. Can somebody guess why it's not working?
ssize_t timeout_recvfrom(int sock, void *restrict buf, size_t length, int flags,
struct sockaddr_in *restrict connection, socklen_t *restrict len, float timeout){
fd_set socks;
struct timeval t;
FD_ZERO(&socks);
FD_SET(sock, &socks);
t.tv_sec = timeout;
int aux = select(sock + 1, &socks, NULL, NULL, &t);
long recvlen = recvfrom(sock, buf, length, 0, (struct sockaddr *) connection, len);
if (aux && recvlen != -1) {
return recvlen;
}
else {
printf("select value: %d and recvlen: %lu\n",aux,recvlen);
perror("cannot select()");
return 0;
}
}
The server calls this function this way:
//recvlen = recvfrom(fd, buf, sizeof(buf) - 1, 0, NULL, 0);
recvlen = timeout_recvfrom(fd, buf, sizeof(buf) - 1, 0, NULL, 0, 0.5);
The commented version works, the other doesn't, it outputs:
select value: 0 and recvlen: 5
cannot select(): Undefined error: 0
Received 0 bytes
Received message: ""
Invalid term: `(null)'
recvlen()
is supposed to have a 5 value, and I guess aux
shouldn't be 0.
Upvotes: 2
Views: 1076
Reputation: 19375
Your call to select returned 0, which means that the timeout expired. You don't initialize the microseconds part of the timeout and since you call the function with 0.5 as the timeout, the seconds part of the seconds part gets initialized to 0 (the microseconds part is probably garbage). – Art
Upvotes: 2