【问题标题】:write() and send() solving errors => difference?write() 和 send() 解决错误 => 区别?
【发布时间】:2012-02-21 08:48:19
【问题描述】:

解决这两个函数之间的错误有什么不同吗?:
这个问题给我带来了另一个问题……字符数总是与字节数相同吗?
有关更多信息:我在 Linux 上的 C 中使用它进行 TCP 套接字通信(sys/socket.h) 感谢您的回复。

send()
write()

返回:
写():
成功时,返回写入的字节数(零表示未写入任何内容)。出错时,返回 -1,并适当设置 errno。如果 count 为零并且文件描述符引用常规文件,则将返回 0 而不会造成任何其他影响。对于特殊文件,结果不可移植。

发送():
调用返回发送的字符数,如果发生错误,则返回 -1。

来自 stackoverflow 的问题说这种方法应该与使用标志零相同。
here

int client_sockfd;
char* msg;
int length = strlen(msg); 

//first option
if(send(client_sockfd, msg, length, 0) != length) return 1;
else return 0;
//second option 
if(write(client_sockfd, msg, length) != length) return 1;
else return 0;

【问题讨论】:

    标签: c sockets send


    【解决方案1】:

    它们都将返回相同数量的写入字节(在这种情况下为 == 字符。除了注意这一点:

    如果消息太长而无法以原子方式通过底层协议,则 返回错误EMSGSIZE,消息不传。

    换句话说,根据正在写入的数据的大小,write() 可能会成功,而 send() 可能会失败。

    【讨论】:

    • write() may succeed where send() may fail,这种行为是否发生在 tcp 套接字上?
    【解决方案2】:

    字节数 == 字符数,因为 C 标准要求 char 是 1 字节整数。

    write(): 是的,它返回写入的字节数。但是:如果它没有返回应写入的字节数,则并不总是错误。特别是不适用于 TCP 通信。套接字可能是非阻塞的或只是忙,在这种情况下,您需要重写尚未写入的字节。这种行为可以这样实现:

    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(): 此处同样适用,唯一的区别是 EOF 通过返回 0 来表示,它 不是 错误。同样,如果您想从套接字接收所有可用数据,则必须重试读取。

    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 */
    

    您可以在https://github.com/H2CO3/TCPHelper/blob/master/TCPHelper.m 看到我使用此技术实现的简单 TCP 帮助程序类

    【讨论】:

    • 对,如果套接字是非阻塞的,规则就会改变。
    • 但是TCP默认处于阻塞模式?所以我不应该这么复杂吗?在这种情况下..
    猜你喜欢
    • 2010-12-19
    • 2015-04-21
    • 2014-01-31
    • 2012-10-24
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    相关资源
    最近更新 更多