write() and send() solving errors => difference?

你说的曾经没有我的故事 提交于 2019-12-05 17:27:38

They will both return the same number of written bytes (== characters in this case. EXCEPT note this:

If the message is too long to pass atomically through the underlying protocol, the error EMSGSIZE is returned, and the message is not transmitted.

In other words, depending on the size of the data being written, write() may succeed where send() may fail.

Number of bytes == number of characters, since the C standard reuires that char be an 1-byte integer.

write(): Yes, it returns the number of bytes written. But: it's not always an error if it doesn't return as many bytes as it should heva written. Especially not for TCP communication. A socket may be nonblocking or simply busy, in which case you'll need to rewrite the not-yet-written bytes. This behavior can be achieved like this:

char *buf = (however you acquire your byte buffer);
ssize_t len = (total number of bytes to be written out);

while (len > 0)
{
    ssize_t written = write(sockfd, buf, len);
    if (written < 0)
    {
        /* now THAT is an error */
        break;
    }
    len -= written;
    buf += written; /* tricky pointer arythmetic */
}

read(): Same applies here, with the only difference that EOF is indicated by returning 0, and it's not an error. Again, you have to retry reading if you want to receive all the available data from a socket.

int readbytes = 0;
char buf[512];
do {
    readbytes = read(sockfd, buf, 512);
    if (readbytes < 0)
    {
        /* error */
        break;
    }
    if (readbytes > 0)
    {
        /* process your freshly read data chunk */
    }
} while (readbytes > 0); /* until EOF */

You can see my implementation of a simple TCP helper class using this technique at https://github.com/H2CO3/TCPHelper/blob/master/TCPHelper.m

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!