refactor(socket): improve read/write
This commit is contained in:
@@ -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
|
||||
|
||||
+39
-21
@@ -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};
|
||||
|
||||
for (;;) {
|
||||
ssize_t n = recv(sockfd, tmp, sizeof tmp, 0);
|
||||
if (n < 0) {
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||
return 0;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (n == 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* 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;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
return total_sent;
|
||||
/* Partial write */
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||
break;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
return (ssize_t)total_sent;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user