我服务器端用tcp发送数据,每次发送1024个byte,客户端用recv接收1024byte,但是客户端实际却会收到528个byte的情况,不知为何?如何解决

jxxfy 2003-02-15 12:44:37
jxradio@sina.com

服务器端:
int nresult = send(listensocket,(const char*)pFrameBuf,1024,0);

客户端:
int ret = recv(mysocket,buf,1024,0);
...全文
280 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
alfwolf 2003-02-15
  • 打赏
  • 举报
回复
你需要多次接收,同时记录每次收到的数据长度。
masterz 2003-02-15
  • 打赏
  • 举报
回复
bool RecvData(SOCKET sd,char* buf,int length)
{
int total = 0;
int readi = 0;
if(length<=0)
return true;
if(buf==NULL)
return false;
while(total<length&&readi>=0)
{
readi = recv(sd,buf+total,length-total,0);
if (readi == SOCKET_ERROR)
{
return false;
}
else
if(readi>0)
total +=readi;
}
if(total==length)
return true;
else
return false;
}

int SendData(SOCKET sd,char* buf,int length)
{ //return 0: OK
//return -1: totalsent out ! = length
//return -2: SOCKET_ERROR
//return 1 : Socket was closed.
int totalsent=0;
int sentnum = 0;
while(totalsent<length)
{
sentnum=send(sd,buf+totalsent,length-totalsent,0);
if(sentnum>0)
totalsent +=sentnum;
else if (sentnum == SOCKET_ERROR)
{
return -2;
}
else
{
// Client closed connection before we could reply to
// all the data it sent, so bomb out early.
return 1;
}
}
if(totalsent == length)
return 0;
else
return -1;
}
zengpan_panpan 2003-02-15
  • 打赏
  • 举报
回复
tcp本来就是流协议,没有报文边界,所以不可能假定客户一次就能收全1024个字节。有多少就收多少串在一起就对了。
jxxfy 2003-02-15
  • 打赏
  • 举报
回复
to JoeRen:是否有什么好的办法?
yins 2003-02-15
  • 打赏
  • 举报
回复
关注
JoeRen 2003-02-15
  • 打赏
  • 举报
回复
上面masterz(MS MVP)的 帖子对于阻塞的调用应该是正确的(我没仔细看)。
但是对于其他的编程模型就有问题了。最有挑战性的是使用重叠发送/接收时使用回调函数进行通知的情况(但这同时也是最灵活和移植性最好的方案!)。
这种情况下需要利用State模式,并记录缓冲区的利用情况,在回调函数中判断缓冲区是否填满,若填满则启动高层的函数进一步处理。
HongHuer 2003-02-15
  • 打赏
  • 举报
回复
int ret = recv(mysocket,buf,1024,0);

试试:
char buffer[1024];
memset(buffer, '\0', sizeof(buffer));
int ret = recv(mysocket,buffer,1024,0);

18,357

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 网络编程
c++c语言开发语言 技术论坛(原bbs)
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧