diff --git a/mongoose.c b/mongoose.c
index 75332c6186887960e149ad00e93e509c4b39ac98..76f35fe34673213e9e6e7d551592287d68b931d7 100644
--- a/mongoose.c
+++ b/mongoose.c
@@ -2895,7 +2895,7 @@ static int mg_do_recv(struct mg_connection *nc) {
     } else {
       res = mg_recv_tcp(nc, buf, len);
     }
-  } while (res > 0);
+  } while (res > 0 && !(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_UDP)));
   return res;
 }
 
@@ -3012,7 +3012,9 @@ static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len) {
       mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV);
     }
 #endif
-    mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n);
+    if (n != 0) {
+      mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n);
+    }
   }
 
 out:
diff --git a/src/mg_net.c b/src/mg_net.c
index 809895c614ac0efa500234b9efeb202e5f072ae6..ebf0513f91ca837676527a3ea3b60df671f5b35d 100644
--- a/src/mg_net.c
+++ b/src/mg_net.c
@@ -578,7 +578,7 @@ static int mg_do_recv(struct mg_connection *nc) {
     } else {
       res = mg_recv_tcp(nc, buf, len);
     }
-  } while (res > 0);
+  } while (res > 0 && !(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_UDP)));
   return res;
 }
 
@@ -695,7 +695,9 @@ static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len) {
       mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV);
     }
 #endif
-    mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n);
+    if (n != 0) {
+      mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n);
+    }
   }
 
 out:
diff --git a/test/unit_test.c b/test/unit_test.c
index cde8df8afc1de2974cd3652735a464b46e170b35..114d20f3e2f27fa6bfe5bd7e4a2dac62f378e565 100644
--- a/test/unit_test.c
+++ b/test/unit_test.c
@@ -5665,7 +5665,7 @@ static const char *test_socks(void) {
   mbuf_resize(&c->recv_mbuf, 10000000);
 
   /* Run event loop. Use more cycles to let file download complete. */
-  poll_until(&mgr, 10, c_str_ne, status, (void *) "");
+  poll_until(&mgr, 15, c_str_ne, status, (void *) "");
   ASSERT_STREQ(status, "success");
 
   mg_mgr_free(&mgr);