服务器端:while(true)
{
char temp[100]; client=accept(server,(struct sockaddr*)&from,&fromlen);
if(client == SOCKET_ERROR)
{
int errorVal = WSAGetLastError(); if(errorVal == WSAENOTCONN)
{

cout<<"socket error"<<endl;
}

WSACleanup();
}
int nResult=recv(client,temp,sizeof(temp),0);
if(nResult!=0){
cout<<"Receive message:"<<temp<<endl;
memset(temp, 0, sizeof(temp));
Sleep(200);
}
客户端:
              nResult=connect(server,(LPSOCKADDR)&local,sizeof(local));
for(int i=0;i<2;i++){
char buf[]="hello,the world";
nResult=send(server,buf,sizeof(buf),0);
if (nResult==SOCKET_ERROR)
{
return false;
}
}
我客户端发送两次buf ,但是服务器段只收到一次,这是什么原因呢,请赐教!

解决方案 »

  1.   

    没有为什么, 只因为TCP是流式协议。
      

  2.   

    服务端:
    int nResult=recv(client,temp,sizeof(temp),0);改为:
    int nResult=recv(client,temp,客户端定义的包长度,0);一般可在包头定义
    struct {
             int buflen;
            }HEAD;
    接收端得时候按照这个长度接收即可。注:Tcp协议是流协议,没有边界。
      

  3.   

    客户端发送两次buf ,但是服务器段只收到一次,这是什么原因呢,请赐教!
    -------------------
    这是因为你的buff不够大,一般情况下TCP的系统buff大小为8129,如果发送两次还未填满这个TCP buff,那么系统只会作为一次发送出去.这就是TCP粘包的缘故.
      

  4.   

    你试试加这个选项看看.
    int on=1;
    setsockopt (ListenSocket,IPPROTO_TCP,TCP_NODELAY,(char*)&on, sizeof on);
      

  5.   

    客端也要加
    int on=1;
    setsockopt (ListenSocket,IPPROTO_TCP,TCP_NODELAY,(char*)&on, sizeof on);如果你要想完全蔽免粘包,你可以用UDP协议来做。
      

  6.   

    recv时候,给一个小点的缓冲吧。
      

  7.   

    你这个是从协议栈中接收一次,是从内核缓冲区拷贝到用户缓冲区一次,很正常,因为系统缓冲区比较大,可以容纳你两次发送的内容。你设置小点的接收缓冲区就ok了啥,比如说一次你接收2Byte,也就是每次从内核缓冲区中拷贝2byte到用户缓冲区,这样你就可以接收多次了...