C/C++網絡編程6——實現基於UDP的服務器端/客戶端

服務器端:ios

 1 #include <iostream>
 2 #include <arpa/inet.h>
 3 #include <sys/socket.h>
 4 #include <unistd.h>
 5 #include <cstring>
 6 
 7 const unsigned int BUFFER_SIZE = 1024;  8 
 9 int main() 10 { 11     // step1:建立UDP套接字
12     int ser_socket = socket(PF_INET, SOCK_DGRAM, 0); 13     if (ser_socket == -1) { 14         std::cout << "socket failed" << std::endl; 15         return 0; 16  } 17 
18     // step2:綁定ip地址和端口號
19  sockaddr_in ser_addr; 20     memset(&ser_addr, 0, sizeof(ser_addr)); 21     ser_addr.sin_family = AF_INET; 22     ser_addr.sin_addr.s_addr = htonl(INADDR_ANY); 23     ser_addr.sin_port = htons(9999); 24     if (bind(ser_socket, (sockaddr *)(&ser_addr), sizeof(ser_addr)) == -1) { 25         std::cout << "bind failed" << std::endl; 26  close(ser_socket); 27         return 0; 28  } 29 
30     char message[BUFFER_SIZE]; 31  sockaddr_in client_addr; 32     socklen_t client_addr_len = sizeof(client_addr_len); 33     int message_len = recvfrom(ser_socket, message, BUFFER_SIZE, 0, 34         (sockaddr*)(&client_addr), &client_addr_len); 35     std::cout << message << std::endl; 36 
37     sendto(ser_socket, message, message_len, 0, 38         (sockaddr *)(&client_addr), client_addr_len); 39  close(ser_socket); 40     return 0; 41 }

客戶端:服務器

 1 #include <iostream>
 2 #include <arpa/inet.h>
 3 #include <sys/socket.h>
 4 #include <unistd.h>
 5 #include <cstring>
 6 
 7 const unsigned int BUFFER_SIZE = 1024;  8 
 9 int main() 10 { 11     // 建立UDP套接字
12     int client_sock = socket(PF_INET, SOCK_DGRAM, 0); 13     if (client_sock == -1) { 14         std::cout << "socket failed" << std::endl; 15         return 0; 16  } 17 
18  sockaddr_in ser_addr; 19     memset(&ser_addr, 0, sizeof(ser_addr)); 20     ser_addr.sin_family = AF_INET; 21     ser_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); 22     ser_addr.sin_port = htons(9999); 23     
24     char info[] = "i love china"; 25     sendto(client_sock, info, sizeof(info), 0, 26         (sockaddr *)(&ser_addr), sizeof(ser_addr)); 27 
28     char message[BUFFER_SIZE]; 29  sockaddr_in from_addr; 30     socklen_t from_addr_len = sizeof(from_addr); 31     recvfrom(client_sock, message, BUFFER_SIZE, 0, 32         (sockaddr*)(&from_addr), &from_addr_len); 33 
34     std::cout << message << std::endl; 35  close(client_sock); 36     return 0; 37 }
相關文章
相關標籤/搜索