[C++] socket - 2 [UDP通信C/S实例]
服务端:
1 #include<iostream> 2 #include<winsock2.h> 3 #include<stdio.h> 4 #pragma comment(lib,"WS2_32.lib")//显示连接套接字库 5 int main() 6 { 7 WSADATA data;//定义WSADATA结构体 8 WORD w=MAKEWORD(2,0);//定义版本号 9 char sztext[]="Welcome you\r\n";//定义并初始化发送到客户端的字符数组 10 ::WSAStartup(w,&data);//初始化套接字库 11 SOCKET s; 12 s=::socket(AF_INET,SOCK_DGRAM,0); 13 sockaddr_in addr,addr2;//定义套接字地址结构 14 int n=sizeof(addr2); 15 char buff[16]={0};//接收数据缓冲区 16 addr.sin_family=AF_INET;//初始化地质结构 17 addr.sin_port=htons(75); 18 addr.sin_addr.S_un.S_addr=INADDR_ANY; 19 ::bind(s,(sockaddr*)&addr,sizeof(addr));//绑定套接字 20 printf("UDP Server already start!\r\n"); 21 if(::recvfrom(s,buff,16,0,(sockaddr*)&addr2,&n)!=-1)//接收客户端信息 22 { 23 printf("%s already connect\r\n",inet_ntoa(addr2.sin_addr)); 24 ::sendto(s,sztext,sizeof(sztext),0,(sockaddr*)&addr2,n);//向客户端发送字符数组 25 ::closesocket(s);//关闭套接字句柄 26 ::WSACleanup();//释放套接字库 27 } 28 if(getchar()) 29 { 30 return 0; 31 } 32 else 33 { 34 ::Sleep(100); 35 } 36 }
客户端:
1 #include<iostream> 2 #include<winsock2.h> 3 #include<stdio.h> 4 #pragma comment(lib,"WS2_32.lib")//显示连接套接字库 5 int main() 6 { 7 WSADATA data;//定义WSADATA结构体 8 WORD w=MAKEWORD(2,0);//定义版本号 9 ::WSAStartup(w,&data);//初始化套接字库 10 SOCKET s; 11 s=::socket(AF_INET,SOCK_DGRAM,0);//创建TCP套接字 12 sockaddr_in addr,addr2; 13 int n=sizeof(addr2); 14 char buff[16]="Wde"; 15 char sztext[16]={0}; 16 addr.sin_family=AF_INET;//初始化地质结构 17 addr.sin_port=htons(75); 18 addr.sin_addr.S_un.S_addr=inet_addr("10.203.117.150"); 19 printf("UDP Clienct already start\r\n"); 20 if(::sendto(s,sztext,sizeof(sztext),0,(sockaddr*)&addr,n)!=0) 21 { 22 ::recvfrom(s,buff,16,0,(sockaddr*)&addr2,&n); 23 printf("Server say:%s\r\n",buff); 24 ::closesocket(s); 25 ::WSACleanup();//释放套接字库 26 } 27 if(getchar()) 28 { 29 return 0; 30 } 31 else 32 { 33 ::Sleep(100); 34 } 35 }