void SendStr(int connfd, std::string str)
{
uint16_t *len = new uint16_t(str.size());
const char * lenByte = (char *)len;
char *sendByte = new char[*len + 2]{0};
memcpy(sendByte,lenByte,sizeof(*len));
memcpy(sendByte + 2, str.c_str(), *len);
std::cout << "str size " << *len << std::endl;
//std::cout << "len size " << sizeof(len) << std::endl;
size_t nleft = *len + 2;
std::cout << "need to send " << nleft << std::endl;
int nsend = 0;
while (nleft > 0)
{
//std::cout << "sending " << nleft << "bytes" << std::endl;
if (nsend = (write(connfd, sendByte + nsend, nleft)) < 0)
{
if (errno == EINTR)
continue;
ERROR_EXIT("send");
}
else if (nsend == 0)
//continue;
break;
nleft -= nsend;
std::cout << "sended " << nsend << " left " << nleft << std::endl;
}
std::cout << "send complete" << std::endl;
delete[] sendByte;
delete len;
}
这里是完整的代码
我看到write和send函数返回字节数的和,而这里返回0,并且客户端似乎运行正常,这让我很困惑。
你看到的不对。
在这份声明中
if (nsend = (write(connfd, sendByte + nsend, nleft)) < 0)
将(write(connfd,sendByte+nsend,nleft))<0
的比较结果与nsend
进行比较。如果条件为true,则该值将变为1
,如果条件为false,则该值将变为0
。看来你误解了这个比较结果是字节的总和。
如果要将从write
返回的内容分配给nsend
然后进行比较,则应该是这样的:
if ((nsend = write(connfd, sendByte + nsend, nleft)) < 0)
补遗:write
在套接字上返回0的唯一方法是,如果nleft
为0。