1

我想使用一个函数,该函数负责通过使用将“数据大小”和“数据”发送到特定文件描述符write()。它在记录长度等于 2 个字节时起作用。但是,我想使用相同的函数发送也等于 1 字节的记录长度。

send_func(int port)
{
    void *fd;
    uint64_t fsize = 2517283;
    uint64_t nbrBytes = 0;  
    uint16_t rsize;
    int count;
    ssize_t ret;
    uint8_t Bsent = 0;

    for (count = 1; nbrBytes < fsize; count++) 
    {
        rsize = ((uint8_t*)fp)[nbrBytes];
        rsize += ((((uint8_t*)fp)[nbrBytes + 1]) << 8) & 0xFF00;
        nbrBytes += 2;

        // send size
        ret = write(port, rsize, 2);
        if (ret != 2) {
            return -1;
        }
        // send data
        ret = write(port, ((unsigned char*)fp) + Bsent, rsize - Bsent);
        if (ret < 0) {
            return -1;
        }
        Bsent += ret;
    }
}

send_func(int port)
{
    void *fd;
    uint64_t fsize = 2517283;
    uint64_t nbrBytes = 0;  
    size_t rsize;
    int count;
    ssize_t ret;
    uint8_t Bsent = 0;

    for (count = 1; nbrBytes < fsize; count++) 
    {
        if (mode == ONLY_1_BYTE) {
            rsize = ((uint8_t*)fp)[nbrBytes];
            rsize += ((((uint8_t*)fp)[nbrBytes + 1])); 
            nbrBytes += 1;

            do {
                // send data
                ret = write(port, ((unsigned char*)fp) + Bsent, rsize - Bsent);
                if (ret < 0) {
                    return -1;
                }  
                Bsent += ret;
            } while(Bsent < rsize)     
        }
        else
        {
            rsize = ((uint8_t*)fp)[nbrBytes];
            rsize += ((((uint8_t*)fp)[nbrBytes + 1]) << 8) & 0xFF00;
            nbrBytes += 2;   

            // send size
            ret = write(port, rsize, sizeof(uint16_t));
            if (ret != 2) {
                return -1;
            }        
        }

        do {
            // send data
            ret = write(port, ((unsigned char*)fp) + Bsent, rsize - Bsent);
            if (ret < 0) {
                return -1;
            }  
            Bsent += ret;
        } while(Bsent < rsize)
    }
}

因为第二种情况只有 1 个长度字节,所以我自愿去掉了字节序操作,这是 2 个字节的情况下必须的。

这是最好的练习方式吗?

4

1 回答 1

1

您可以应用一些最佳实践来改进您发布的代码:

  • 不要担心优化流中的单个字节。没关系。您是否知道除了有效负载之外,每个以太网帧都需要大约 60 字节的开销?
  • 不要手动滚动字节序交换。使用内置函数,如htons().
  • 您需要考虑返回值write()小于您尝试发送的“短写入”。发生这种情况时,您需要循环并write()再次调用而不重新发送长度前缀。
于 2015-12-15T16:05:36.833 回答