C++之UDP通信例程

C++之UDP通信例程


UDP(User Datagram Protocol,用户数据报协议)是一种无连接的传输层协议,它不像TCP那样提供可靠的数据传输服务,但具有简单、快速的特点。在C++中使用UDP协议进行通信,需要使用Socket编程。

以下是一个简单的C++ UDP通信例程,包括UDP服务端和客户端:

UDP服务端:

#include   
#include   
#include   
#include   
#include   
#include   
#include   
  
#define MAX_BUFFER_SIZE 1024  
#define PORT 8888  
  
int main() {  
    int sockfd;  
    struct sockaddr_in server_addr, client_addr;  
    char buffer[MAX_BUFFER_SIZE];  
    int addrlen = sizeof(client_addr);  
      
    // 创建UDP套接字  
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {  
        perror("socket");  
        exit(EXIT_FAILURE);  
    }  
      
    // 初始化服务器地址信息  
    memset(&server_addr, 0, sizeof(server_addr));  
    server_addr.sin_family = AF_INET;  
    server_addr.sin_port = htons(PORT);  
    server_addr.sin_addr.s_addr = INADDR_ANY;  
      
    // 绑定服务器地址信息到套接字  
    if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {  
        perror("bind");  
        exit(EXIT_FAILURE);  
    }  
      
    std::cout << "Server is running on port " << PORT << std::endl;  
      
    while (true) {  
        // 接收客户端数据  
        int n = recvfrom(sockfd, (char *)buffer, MAX_BUFFER_SIZE, MSG_WAITALL, (struct sockaddr *)&client_addr, &addrlen);  
        buffer[n] = '\0';  
        std::cout << "Received message from client " << inet_ntoa(client_addr.sin_addr) << ": " << buffer << std::endl;  
    }  
      
    close(sockfd);  
    return 0;  
}

UDP客户端:

#include   
#include   
#include   
#include   
#include   
#include   
#include   
  
#define MAX_BUFFER_SIZE 1024  
#define PORT 8888  
#define SERVER_IP "127.0.0.1"  
  
int main() {  
    int sockfd;  
    struct sockaddr_in server_addr;  
    char buffer[MAX_BUFFER_SIZE];  
    int addrlen = sizeof(server_addr);  
      
    // 创建UDP套接字  
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {  
        perror("socket");  
        exit(EXIT_FAILURE);  
    }  
      
    // 初始化服务器地址信息  
    memset(&server_addr, 0, sizeof(server_addr));  
    server_addr.sin_family = AF_INET;  
    server_addr.sin_port = htons(PORT);  
    if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) == 0) {  
        perror("inet_pton");  
        exit(EXIT_FAILURE);  
    }  
      
    std::cout << "Client is running on port " << PORT << std::endl;  
    std::cout << "Please input message to send to server: ";  
    std::cin.getline(buffer, MAX_BUFFER_SIZE);  
    sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));  
    std::cout << "Message sent to server: " << buffer << std::endl;  
    close(sockfd);

你可能感兴趣的:(c++,udp,开发语言,网络协议)