我想使用一个函数,它使用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个字节的情况下是强制性的。
这是最好的练习方法吗?
答案 0 :(得分:1)
您可以应用一些最佳做法来改进您发布的代码:
htons()
。write()
的返回值小于您尝试发送的值。当发生这种情况时,您需要循环并再次呼叫write()
,而无需重新发送长度前缀。