服务端:
#pragma comment (lib,"ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData;
int error=WSAStartup(MAKEWORD(1,1),&wsaData);
if(error!=0)
{
return -1;
}
if(LOBYTE(wsaData.wVersion)!=1 || HIBYTE(wsaData.wVersion)!=1)
{
WSACleanup();
return -1;
}
SOCKET s=socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN sockSrc;
sockSrc.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
sockSrc.sin_port=htons(8888);
sockSrc.sin_family=AF_INET;
bind(s,(SOCKADDR *)&sockSrc,sizeof(SOCKADDR));
unsigned char recBuff[32*1024];
setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char*)&recBuff,sizeof(int));
memset(recBuff,0,32*1024);
SOCKADDR_IN sockRec;
int len=sizeof(SOCKADDR);
int x=-1;
int i = 1;
FILE* pf;
if(0 != fopen_s(&pf, ".//receive.txt","a+"))
{
printf("fopen error!\n");
}
while(1)
{
x=recvfrom(s,(char*)recBuff,sizeof(recBuff),0,(sockaddr *)&sockRec,&len);
printf("the receive is:\n");
for(int i = 0; i < x; i++)
{
printf("%d",recBuff[i]);
}
printf("\n");
fwrite(recBuff,x,1,pf);
memset(recBuff,0,32*1024);
printf("receive:%d num is %d============================\n",x,i++);
}
closesocket(s);
fclose(pf);
WSACleanup();
return 0;
}
客户端:
#include "stdafx.h"
#pragma comment (lib,"ws2_32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return -1;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||HIBYTE( wsaData.wVersion ) != 1 )
{
WSACleanup( );
return -1;
}
SOCKET sockClient=socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr("192.168.31.127");
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(8888);
while(1)
{
sendto(sockClient,"Hello",strlen("Hello")+1,0,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
}
closesocket(sockClient);
WSACleanup();
return 0;
}
服务端发送的数据是5*256个char数据,在编写服务端的时候,我把缓存区设置为char [2000];然后打印每次收到的数据。然后发现有丢包现象。后来经指导。讲缓存区改大了。问题就解决了。
在编写服务端的时候,我把缓存区设置为char [2000];用来接收服务端发送过来的数据。服务端
int nRecvBuf=32*1024;//设置为32K,改一下设置
然后通过setsockopt这个函数来通知socket。
setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char*)&nRecvBuf,sizeof(int));