aboutsummaryrefslogtreecommitdiff
path: root/protocol.c
diff options
context:
space:
mode:
authorsotech117 <michael_foiani@brown.edu>2023-09-23 17:30:45 -0400
committersotech117 <michael_foiani@brown.edu>2023-09-23 17:30:45 -0400
commit3b2aa8c271bf5cd5497decb6577afe5fd7339f57 (patch)
treebc1d39ad76b15f58ddf61385645fa87a59fb1157 /protocol.c
parentb417bcc57b9fd49f360087c32c97293a6bc7d2be (diff)
parent1e9ac5407ef4f2cddc745f35f33a860446526cea (diff)
merge post-warmup with main
Diffstat (limited to 'protocol.c')
-rw-r--r--protocol.c66
1 files changed, 66 insertions, 0 deletions
diff --git a/protocol.c b/protocol.c
new file mode 100644
index 0000000..d350221
--- /dev/null
+++ b/protocol.c
@@ -0,0 +1,66 @@
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#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;
+
+ while(total < *len) {
+ n = send(sock, buf+total, bytesleft, 0);
+ if (n == -1) { break; }
+ total += n;
+ bytesleft -= n;
+ }
+
+ *len = total; // return number actually sent here
+
+ return n==-1?-1:0; // return -1 on failure, 0 on success
+}
+
+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
+}