在阻塞套接字上读写

即使套接字处于阻塞模式,对它们的 readwrite 操作也不必读写所有可读取或写入的数据。为了将整个缓冲区写入套接字,或从套接字读取已知数量的数据,必须在循环中调用它们。

/*
 * Writes all bytes from buffer into sock. Returns true on success, false on failure.
 */
bool write_to_socket(int sock, const char* buffer, size_t size) {
    size_t total_bytes = 0;
    while(total_bytes < size) {
        ssize_t bytes_written = write(sock, buffer + total_bytes, size - total_bytes);
        if(bytes_written >= 0) {
            total_bytes += bytes_written;
        } else if(bytes_written == -1 && errno != EINTR) {
            return false;
        }
    }
    return true;
}
/*
 * Reads size bytes from sock into buffer. Returns true on success; false if
 * the socket returns EOF before size bytes can be read, or if there is an
 * error while reading.
 */
bool read_from_socket(int sock, char* buffer, size_t size) {
    size_t total_bytes = 0;
    while(total_bytes < size) {
        ssize_t new_bytes = read(sock, buffer + total_bytes, size - total_bytes);
        if(new_bytes > 0) {
            total_bytes += new_bytes;
        } else if(new_bytes == 0 || (new_bytes == -1 && errno != EINTR)) {
            return false;
        }
    }
    return true;
}