客户端
#include "winsock2.h"
#include "stdlib.h"
#include "stdio.h"
#include "conio.h"
#include "windows.h"
main()
{
WORD wVersionRequested;
WSADATA lpWSAData;
WSAStartup(
wVersionRequested,
&lpWSAData
);
SOCKET serversocket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
int ret=GetLastError();
ret=GetLastError();
char buff[21]={"12345678900987654321"};
struct sockaddr_in addrin2;
addrin2.sin_family=AF_INET;
addrin2.sin_addr.S_un.S_addr=inet_addr("11.39.109.76");
addrin2.sin_port=htons(7777);
int len=(int)sizeof(addrin2);
int count=0;
int count2;
while(count<1000)
{
//memcpy(buff,&count,4);
sendto(serversocket,buff,20,0,(struct sockaddr*)&addrin2,len);
//Sleep(100);
count++;
char buff2[10]={0};
recvfrom(serversocket,(char*)&count2,4,0,(struct sockaddr*)&addrin2,&len);
//count=count2;
}
}
服务端
#include "winsock2.h"
#include "stdlib.h"
#include "stdio.h"
main()
{
WORD wVersionRequested;
WSADATA lpWSAData;
WSAStartup(
wVersionRequested,
&lpWSAData
);
SOCKET serversocket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
int ret=GetLastError();
struct sockaddr_in addrin;
addrin.sin_addr.S_un.S_addr=INADDR_ANY;//inet_addr("127.0.0.1");
addrin.sin_family=AF_INET;
addrin.sin_port=htons(7777);
if(bind(serversocket, (struct sockaddr FAR *) &addrin, sizeof(addrin))==SOCKET_ERROR)
{
// this->m_listresult.AddString("绑定失败");
return -1;
}
ret=GetLastError();
char buff[21]={0};
struct sockaddr_in addrin2;
addrin2.sin_family=AF_INET;
//addrin2.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
addrin2.sin_port=htons(7777);
int len=(int)sizeof(addrin2);
int count=0;
while(true)
{
recvfrom(serversocket,buff,20,0,(struct sockaddr*)&addrin2,&len);
//count=((int*)buff)[0];
printf("==============/n%s/n=================IP 0x%x===count= %d====/n",buff+4,addrin2.sin_addr.S_un.S_addr,count);
count++;
sendto(serversocket,(char*)&count,4,0,(struct sockaddr*)&addrin2,len);
}
}
UDP和TCP相比需要自己进行流量控制,如上面所述,如果客户端发送后接收服务端数据的代码去掉之后,可以明显的看到数据丢失
对于UDP的时候我还没有对接收数据乱序的情况进行过测试,不过感觉在一些简单的通信中,用UDP还蛮好