Browse Source

Resolve partial sends

Samuel Čavoj 2 years ago
parent
commit
e6a86e8cb7
4 changed files with 23 additions and 8 deletions
  1. 5 4
      client.c
  2. 12 0
      network.c
  3. 1 0
      network.h
  4. 5 4
      server.c

+ 5 - 4
client.c

@@ -88,8 +88,8 @@ void send_hello() {
     uint8_t packet[3];
     *((uint16_t*)packet) = htons(3);
     packet[2] = PKT_TYPE_HELLO;
-    if (send(g_sockfd, packet, sizeof packet, 0) == -1) {
-        perror("send");
+    if (send_packet(g_sockfd, packet, sizeof packet) < (sizeof packet)) {
+        perror("send_packet");
         exit(EXIT_FAILURE);
     }
 }
@@ -128,8 +128,9 @@ void put_char_usr(int y, int x, char ch) {
         .ch = ch
     };
 
-    if (send(g_sockfd, &packet, sizeof(struct packet_update_t), 0) == -1) {
-        perror("send");
+    size_t len = sizeof(struct packet_update_t);
+    if (send_packet(g_sockfd, (uint8_t*)&packet, len) < len) {
+        perror("send_packet");
         exit(EXIT_FAILURE);
     }
 

+ 12 - 0
network.c

@@ -63,3 +63,15 @@ int recv_dump(int fd) {
     char buf[PKT_SIZE_MAX];
     return recv(fd, buf, PKT_SIZE_MAX, 0);
 }
+
+size_t send_packet(int fd, uint8_t* buf, size_t length) {
+    size_t sent = 0;
+    int n;
+    while (sent < length) {
+        if ((n = send(fd, buf+sent, length-sent, 0)) == -1) {
+            return sent;
+        }
+        sent += n;
+    }
+    return sent;
+}

+ 1 - 0
network.h

@@ -34,3 +34,4 @@ assert_packet_size(packet_init_t)
 int recv_packet(int fd, uint8_t* buf, size_t* n);
 int recv_dump_all(int fd);
 int recv_dump(int fd);
+size_t send_packet(int fd, uint8_t* buf, size_t length);

+ 5 - 4
server.c

@@ -158,8 +158,9 @@ int main(int argc, char *argv[]) {
                         };
                         memcpy(&pkt_init.data, FIELD, sizeof(pkt_init.data));
                         printf("sending init\n");
-                        if (send(fd, &pkt_init, sizeof(struct packet_init_t), 0) == -1) {
-                            perror("send");
+                        size_t pkt_len = sizeof(struct packet_init_t);
+                        if (send_packet(fd, (uint8_t*)&pkt_init, pkt_len) < pkt_len) {
+                            perror("send_packet");
                         }
                     } else if (type == PKT_TYPE_UPDATE) {
                         struct packet_update_t *pkt = (struct packet_update_t *)buf;
@@ -173,8 +174,8 @@ int main(int argc, char *argv[]) {
                                 continue;
                             }
                             if (FD_ISSET(j, &fds_master)) {
-                                if (send(j, buf, len, 0) == -1) {
-                                    perror("send");
+                                if (send_packet(j, buf, len) < len) {
+                                    perror("send_packet");
                                 }
                             }
                         }