|
简单的一批
客户Duan
WSAData wd={0};
WSAStartup(MAKEWORD(2,2),&wd);
SOCKET clients=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
sockaddr_in si={0};
si.sin_addr.s_addr=inet_addr("xxx.xxx.xxx.xxx");//这里填你自己服务器IP
si.sin_family=AF_INET;
si.sin_port=htons(3500);
char* pbuffer=new char[1024*1024]();
while(true){
cout<<"请输入要发送的内容:"<<endl;
cin>>pbuffer;
sendto(clients,pbuffer,strlen(pbuffer),0,(sockaddr*)&si,sizeof(si));
ZeroMemory(pbuffer,1024*1024);
int recvlen=recvfrom(clients,pbuffer,1024*1024,0,NULL,NULL);
if(recvlen>0)
printf("服务端说:%s\n",pbuffer);
else if(recvlen==0 || recvlen==SOCKET_ERROR)//0正常退出
break;
ZeroMemory(pbuffer,1024*1024);
}
return 0;
服务端
WSAData wd={0};
WSAStartup(MAKEWORD(2,2),&wd);
SOCKET servers=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
sockaddr_in si={0};
si.sin_addr.s_addr=htonl(INADDR_ANY);
si.sin_family=AF_INET;
si.sin_port=htons(3500);
bind(servers,(sockaddr*)&si,sizeof(si));
char* pbuffer=new char[1024*1024]();
sockaddr_in si2={0};
int si2len=sizeof(si2);
while(true){
int recvlen=recvfrom(servers,pbuffer,1024*1024,0,(sockaddr*)&si2,&si2len);
if(recvlen>0)
{printf("%s\n",pbuffer);sendto(servers,"服务器发送的消息",16,0,(sockaddr*)&si2,si2len);}
if(recvlen==SOCKET_ERROR || recvlen==0)//0正常退出
break;
Sleep(100);
ZeroMemory(pbuffer,1024*1024);
}
delete[] pbuffer;
WSACleanup();
return 0;
|
|