服务器端: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 ,但是服务器段只收到一次,这是什么原因呢,请赐教!
{
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 ,但是服务器段只收到一次,这是什么原因呢,请赐教!
int nResult=recv(client,temp,sizeof(temp),0);改为:
int nResult=recv(client,temp,客户端定义的包长度,0);一般可在包头定义
struct {
int buflen;
}HEAD;
接收端得时候按照这个长度接收即可。注:Tcp协议是流协议,没有边界。
-------------------
这是因为你的buff不够大,一般情况下TCP的系统buff大小为8129,如果发送两次还未填满这个TCP buff,那么系统只会作为一次发送出去.这就是TCP粘包的缘故.
int on=1;
setsockopt (ListenSocket,IPPROTO_TCP,TCP_NODELAY,(char*)&on, sizeof on);
int on=1;
setsockopt (ListenSocket,IPPROTO_TCP,TCP_NODELAY,(char*)&on, sizeof on);如果你要想完全蔽免粘包,你可以用UDP协议来做。