在阻塞套接字上讀寫
即使套接字處於阻塞模式,對它們的 read
和 write
操作也不必讀寫所有可讀取或寫入的資料。為了將整個緩衝區寫入套接字,或從套接字讀取已知數量的資料,必須在迴圈中呼叫它們。
/*
* 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;
}