aboutsummaryrefslogtreecommitdiff
path: root/protocol.c
diff options
context:
space:
mode:
authorsotech117 <michael_foiani@brown.edu>2023-09-21 07:06:14 +0000
committersotech117 <michael_foiani@brown.edu>2023-09-21 07:06:14 +0000
commit9ba49f755e152d0996a43e8da7d146b8d2069051 (patch)
treedde7fe228fc6ab44c3c462576a391193e3189da5 /protocol.c
parent433f6eb3a54881913286aa620db93c003c436c16 (diff)
add timeout
Diffstat (limited to 'protocol.c')
-rw-r--r--protocol.c26
1 files changed, 26 insertions, 0 deletions
diff --git a/protocol.c b/protocol.c
index 864afd8..d350221 100644
--- a/protocol.c
+++ b/protocol.c
@@ -3,8 +3,17 @@
#include "protocol.h"
+#define TIMEOUT 100000 // 100ms in microseconds
+
int send_all(int sock, char *buf, int *len)
{
+ struct timeval timeout;
+ timeout.tv_sec = 0;
+ timeout.tv_usec = 100000;
+ // if (setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, &timeout,
+ // sizeof timeout) < 0)
+ // perror("setsockopt failed\n");
+
int total = 0; // how many bytes we've sent
int bytesleft = *len; // how many we have left to send
int n;
@@ -23,17 +32,34 @@ int send_all(int sock, char *buf, int *len)
int recv_all(int sock, char *buf, int *len)
{
+ // setup the timeout on the socket
+ struct timeval timeout;
+ timeout.tv_sec = 0;
+ timeout.tv_usec = TIMEOUT;
+ if (setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, &timeout,
+ sizeof timeout) < 0)
+ perror("setsockopt failed\n");
+
+ // printf("start: %ld\n", start);
int total = 0; // how many bytes we've sent
int bytesleft = *len; // how many we have left to send
int n;
while(total < *len) {
n = recv(sock, buf+total, bytesleft, 0);
+ // start = time(NULL);
if (n == -1) { break; }
total += n;
bytesleft -= n;
}
+ timeout.tv_sec = 0;
+ timeout.tv_usec = 0;
+ if (setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, &timeout,
+ sizeof timeout) < 0)
+ perror("setsockopt failed\n");
+
+
*len = total; // return number actually sent here
return n==-1?-1:0; // return -1 on failure, 0 on success