阅读总是比要求阅读的八位字节少
read always read less octet than asked
为了家庭作业,我必须创建一个 client/server 程序来存储数据。客户端读取文件并通过套接字发送给服务器,服务器接收并存储数据。最终目标是在多个服务器之间实现分片。
该程序运行良好,但当客户端和服务器不在同一台机器上时,读取功能总是读取的数据少于我要求的数据
这是我的阅读代码:
static inline size_t reliableRead(const int sourceSocket, void* data, const size_t nBytes)
{
size_t dataRead = 0;
unsigned int lossInARaw = 0;
do
{ const size_t readStatus = read(sourceSocket,data+dataRead,nBytes - dataRead);
if (readStatus == (unsigned)-1)
{
LOG_ERRNO_ERROR("error on read");
break;
}
dataRead += readStatus;
if (readStatus != nBytes)
LOG_WARNING("data loss(%u): read %zu/%zuo",++lossInARaw,dataRead,nBytes);
} while (dataRead < nBytes);
return dataRead;
}
这是我尝试读取 1024o 然后 8192o 块时的结果。首先客户端和服务器是两个不同的主机,然后在同一个
服务器端,当从另一台机器上的客户端接收到以 1024o 为单位的数据块时
服务器端,当从另一台机器上的客户端接收到以 8192o 为单位的数据块时
服务器端接收数据时客户端也在本机
从图像上看,read显然能够读取1024o以上。我以前从未进行过套接字编程,所以也许我遗漏了一些东西,我怎样才能让读取函数更频繁地读取我要求它读取的数据量?因为即使不显示警告,这也明显增加了发送时间(不要介意计时消息,它显然已关闭,我会处理的)
对于 recv
,而不是 read
,POSIX 指定 MSG_WAITALL
flag,您应该能够使用它来防止不必要的上下文切换到您的线程,当所有它会做的只是 re-request would-be-partial read
.
的剩余部分
MSG_WAITALL On SOCK_STREAM sockets this requests that the function
block until the full amount of data can be returned. The function may
return the smaller amount of data if the socket is a message-based
socket, if a signal is caught, if the connection is terminated, if
MSG_PEEK was specified, or if an error is pending for the socket.
为了家庭作业,我必须创建一个 client/server 程序来存储数据。客户端读取文件并通过套接字发送给服务器,服务器接收并存储数据。最终目标是在多个服务器之间实现分片。 该程序运行良好,但当客户端和服务器不在同一台机器上时,读取功能总是读取的数据少于我要求的数据
这是我的阅读代码:
static inline size_t reliableRead(const int sourceSocket, void* data, const size_t nBytes)
{
size_t dataRead = 0;
unsigned int lossInARaw = 0;
do
{ const size_t readStatus = read(sourceSocket,data+dataRead,nBytes - dataRead);
if (readStatus == (unsigned)-1)
{
LOG_ERRNO_ERROR("error on read");
break;
}
dataRead += readStatus;
if (readStatus != nBytes)
LOG_WARNING("data loss(%u): read %zu/%zuo",++lossInARaw,dataRead,nBytes);
} while (dataRead < nBytes);
return dataRead;
}
这是我尝试读取 1024o 然后 8192o 块时的结果。首先客户端和服务器是两个不同的主机,然后在同一个
服务器端,当从另一台机器上的客户端接收到以 1024o 为单位的数据块时
服务器端,当从另一台机器上的客户端接收到以 8192o 为单位的数据块时
服务器端接收数据时客户端也在本机
从图像上看,read显然能够读取1024o以上。我以前从未进行过套接字编程,所以也许我遗漏了一些东西,我怎样才能让读取函数更频繁地读取我要求它读取的数据量?因为即使不显示警告,这也明显增加了发送时间(不要介意计时消息,它显然已关闭,我会处理的)
对于 recv
,而不是 read
,POSIX 指定 MSG_WAITALL
flag,您应该能够使用它来防止不必要的上下文切换到您的线程,当所有它会做的只是 re-request would-be-partial read
.
MSG_WAITALL On SOCK_STREAM sockets this requests that the function block until the full amount of data can be returned. The function may return the smaller amount of data if the socket is a message-based socket, if a signal is caught, if the connection is terminated, if MSG_PEEK was specified, or if an error is pending for the socket.