C ++ Socket recv没有收到正确的字节数? [英] C++ Socket recv not receiving correct number of bytes?

查看:500
本文介绍了C ++ Socket recv没有收到正确的字节数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,但我想学习一些TCP套接字编码的基础知识。无论如何,我已经能够发送和接收消息,但我想在我的数据包前面的长度的包(像我在过去的C#应用​​程序),所以当我的窗口获得FD_READ命令,我有以下代码只读取数据包的前两个字节,以作为短整型。

  char lengthBuffer [2] 

int rec = recv(sck,lengthBuffer,sizeof(lengthBuffer),0);

short unsigned int toRec = lengthBuffer [1]< 8 | lengthBuffer [0];有什么让我困惑的是,一个数据包进入'rec'变量后,它说了多少字节?读取的是一个,而不是两个,如果我使lengthBuffer三个字符而不是两个,它读取三个字节,但如果它是四,它也读取三(只有奇数)。我不能告诉我在这里做一些真正的愚蠢的错误,或从根本上误解语言或API的某些部分。我知道recv不保证任何数量的字节将被读取,但如果它只是两个,它不应该多次读取。

解决方案

因为你不能假定有多少数据可用,你需要不断地从套接字读取,直到你有你想要的数量。这样的东西应该工作:

  ssize_t rec = 0; 
do {
int result = recv(sck,& lengthBuffer [rec],sizeof(lengthBuffer) - rec,0);
if(result == -1){
//处理错误...
break;
}
else if(result == 0){
//句柄断开...
break;
}
else {
rec + = result;
}
}
while(rec< sizeof(lengthBuffer));


I'm very new to C++, but I'm trying to learn some basics of TCP socket coding. Anyway, I've been able to send and receive messages, but I want to prefix my packets with the length of the packet (like I did in C# apps I made in the past) so when my window gets the FD_READ command, I have the following code to read just the first two bytes of the packet to use as a short int.

char lengthBuffer[2];

int rec = recv(sck, lengthBuffer, sizeof(lengthBuffer), 0);

short unsigned int toRec = lengthBuffer[1] << 8 | lengthBuffer[0];

What's confusing me is that after a packet comes in the 'rec' variable, which says how many bytes were read is one, not two, and if I make the lengthBuffer three chars instead of two, it reads three bytes, but if it's four, it also reads three (only odd numbers). I can't tell if I'm making some really stupid mistake here, or fundamentally misunderstanding some part of the language or the API. I'm aware that recv doesn't guarantee any number of bytes will be read, but if it's just two, it shouldn't take multiple reads.

解决方案

Because you cannot assume how much data will be available, you'll need to continuously read from the socket until you have the amount you want. Something like this should work:

ssize_t rec = 0;
do {
    int result = recv(sck, &lengthBuffer[rec], sizeof(lengthBuffer) - rec, 0);
    if (result == -1) {
        // Handle error ...
        break;
    }
    else if (result == 0) {
        // Handle disconnect ...
        break;
    }
    else {
        rec += result;
    }
}
while (rec < sizeof(lengthBuffer));

这篇关于C ++ Socket recv没有收到正确的字节数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆