c++ - 如何判断read函数是否完整读完?
ringa_lee
ringa_lee 2017-04-17 13:16:18
0
3
970
#define MAX 500

char _readbuf[MAX];

while (read(socket_fd, _readbuf, MAX) > 0)
{
    printf("%s", _readbuf);
    if (strlen(_readbuf) < MAX) // 我用这种方式来判断是否读完
           break;
    memset(_readbuf, 0, MAX);
}

但是如果网速慢或者对方主机当掉的话,这样又读不完整了,就是不会一次性发满给你,分一点点发,那我这样判断是否读完又不行了。请问用read函数怎么实现完整读完对方发来的数据?

再具体一点,我在实现一个ftp客户端,比如我向服务端发送一个HELP命令,服务器会返回一串字符串的,结尾肯定是\r\n,但不保证\r\n出现一次,是否能判断逻辑读完?其实我就是不知道如何判断read是否完整读完。因为它就是返回一个字符串,能用EOF判断吗?

ringa_lee
ringa_lee

ringa_lee

reply all(3)
洪涛

根据read的返回值判断:
size = read(somefd, someBuffer, length);
size > 0 //size就是实际读到的长度
size == 0 //读到eof了,读取结束
size < 0 //发生错误,要检查errno

man 2 read:
RETURN VALUE
On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is returned, and errno is set appropriately. In this case, it is left unspecified whether the file position (if any) changes.

巴扎黑

Socket is actually a stream. With a stream, you have no way to judge whether it is finished reading. You read several bytes from the stream at a time, and then judge whether the packet is complete at the logical layer. This is the only way. So the logic The layer needs to have a separate buffer to store the packets that have not been fully decoded. After the reading is complete, they will be decoded and released.

左手右手慢动作

What is 完整读完 is difficult to define, it is very vague.
What communication protocol are used by both parties? What should be stipulated in the agreement? “读完了”

Just like @beardedold man and @egmkang said

  • Anyway, if read returns 0, it means EOF. In the socket, it means that the other party has closed the connection. There are many reasons for closing the connection, such as: thinking that your connection is illegal, an error has occurred, or “发送完毕”, anyway, it is the other party有意的、主动的关闭了连接

  • The read return value greater than 0 indicates how many bytes were read this time

  • The return value of read is less than 0, which means an error occurred. You can know the cause of the error by looking at errno, such as Timeout and other reasons

As for 一次读不完, 一次发不满, and 一点儿一点儿发, then just cache them! , until EOF or logical judgment 读完 is read.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template