refactor(socket): improve read/write

This commit is contained in:
2026-03-25 01:56:06 +01:00
parent 3cb8fda44d
commit 6ef810f511
2 changed files with 42 additions and 24 deletions
+2 -2
View File
@@ -4,8 +4,8 @@
#include <myclib/mystring.h>
#include <sys/types.h>
ssize_t cws_socket_read(int sockfd, string_s *str);
int cws_socket_read(int sockfd, string_s *str);
ssize_t cws_socket_send(int sockfd, const char *buffer, size_t len, int flags);
int cws_socket_send(int sockfd, const char *buffer, size_t len, int flags);
#endif
+40 -22
View File
@@ -3,46 +3,64 @@
#include <errno.h>
#include <sys/socket.h>
ssize_t cws_socket_read(int sockfd, string_s *str) {
int cws_socket_read(int sockfd, string_s *str) {
char tmp[4096] = {0};
ssize_t n = recv(sockfd, tmp, sizeof tmp, 0);
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
for (;;) {
ssize_t n = recv(sockfd, tmp, sizeof tmp, 0);
/* We have some data */
if (n > 0) {
tmp[n] = '\0';
string_append(str, tmp);
return n;
}
/* Client closed */
if (n == 0) {
return 0;
}
if (errno == EINTR) {
continue;
}
/* No data now */
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return -2;
}
/* Something happened */
return -1;
}
if (n == 0) {
return -1;
}
tmp[n] = '\0';
string_append(str, tmp);
return n;
}
ssize_t cws_socket_send(int sockfd, const char *buffer, size_t len, int flags) {
int cws_socket_send(int sockfd, const char *buffer, size_t len, int flags) {
size_t total_sent = 0;
ssize_t n;
while (total_sent < len) {
n = send(sockfd, buffer + total_sent, len - total_sent, flags);
ssize_t n = send(sockfd, buffer + total_sent, len - total_sent, flags);
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
return -1;
if (n > 0) {
total_sent += (size_t)n;
continue;
}
if (n == 0) {
break;
}
total_sent += n;
if (errno == EINTR) {
continue;
}
/* Partial write */
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
return -1;
}
return total_sent;
return (ssize_t)total_sent;
}