• C++之基于Winsock2封装UDPServer与UDPClient


    Socket过程

    • UDPServer

    • UDPClient

    UDPServer.h

    #ifndef UDPSERVER_H_INCLUDED
    #define UDPSERVER_H_INCLUDED
    
    #include 
    #include 
    #include 
    
    class UDPServer
    {
    private:
        WORD sockVersion;
        WSADATA wsaData;
        SOCKET udpSocket;
        sockaddr_in localAddr;
        sockaddr_in remoteAddr; // Client
        const int MSG_SIZE = 1024;
    
    public:
        UDPServer();
        ~UDPServer();
        void Bind(u_short port);
        void Receive();
        bool Send(std::string message);
    };
    
    #endif // UDPSERVER_H_INCLUDED
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    UDPServer.cpp

    #include "UDPServer.h"
    
    UDPServer::UDPServer()
    {
        sockVersion = MAKEWORD(2, 2);
        WSAStartup(sockVersion, &wsaData);
        udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    }
    
    UDPServer::~UDPServer()
    {
        closesocket(udpSocket);
        WSACleanup();
    }
    
    void UDPServer::Bind(u_short port)
    {
        localAddr.sin_family = AF_INET;
        localAddr.sin_port = htons(port);
        // localAddr.sin_addr.S_un.S_addr = INADDR_ANY; // 0.0.0.0
        localAddr.sin_addr.S_un.S_addr = inet_addr("0.0.0.0");
        bind(udpSocket, (const sockaddr *)&localAddr, sizeof(localAddr));
    }
    
    void UDPServer::Receive()
    {
        while (true)
        {
            char recvBuffer[MSG_SIZE];
            int localAddrSize = sizeof(localAddr);
            int lenRemoteAddr = sizeof(remoteAddr);
            int len = recvfrom(udpSocket, recvBuffer, MSG_SIZE, 0, (SOCKADDR *)&remoteAddr, &lenRemoteAddr);
            if (len > 0)
            {
                recvBuffer[len] = '\0';
                std::cout << "[" << inet_ntoa(remoteAddr.sin_addr) << ":" << remoteAddr.sin_port << "] -> " << recvBuffer << std::endl;
            }
        }
    }
    
    bool UDPServer::Send(std::string message)
    {
        int ret = sendto(udpSocket, message.c_str(), message.length(), 0, (sockaddr *)&remoteAddr, sizeof(remoteAddr));
        if (ret == SOCKET_ERROR)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    UDPClient.h

    #ifndef UDPCLIENT_H_INCLUDED
    #define UDPCLIENT_H_INCLUDED
    
    #include 
    #include 
    #include 
    
    class UDPClient
    {
    private:
        WORD sockVersion;
        WSADATA wsaData;
        SOCKET udpSocket;
        sockaddr_in localAddr;
        sockaddr_in remoteAddr; // Client
        const int MSG_SIZE = 1024;
    
    public:
        UDPClient();
        ~UDPClient();
        void Bind(std::string ip, u_short port);
        void Receive();
        bool Send(std::string message);
    };
    
    #endif // UDPCLIENT_H_INCLUDED
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    UDPClient.cpp

    #include "UDPClient.h"
    
    UDPClient::UDPClient()
    {
        sockVersion = MAKEWORD(2, 2);
        WSAStartup(sockVersion, &wsaData);
        udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    }
    
    UDPClient::~UDPClient()
    {
        closesocket(udpSocket);
        WSACleanup();
    }
    
    void UDPClient::Bind(std::string ip, u_short port)
    {
        localAddr.sin_family = AF_INET;
        localAddr.sin_port = htons(port);
        localAddr.sin_addr.S_un.S_addr = INADDR_ANY; // 0.0.0.0
        remoteAddr = localAddr;
        remoteAddr.sin_addr.S_un.S_addr = inet_addr(ip.c_str());
        bind(udpSocket, (const sockaddr *)&localAddr, sizeof(localAddr));
        Send("Hello");
    }
    
    void UDPClient::Receive()
    {
        while (true)
        {
            char recvBuffer[MSG_SIZE];
            int localAddrSize = sizeof(localAddr);
            int lenRemoteAddr = sizeof(remoteAddr);
            int len = recvfrom(udpSocket, recvBuffer, MSG_SIZE, 0, (SOCKADDR *)&remoteAddr, &lenRemoteAddr);
            if (len > 0)
            {
                recvBuffer[len] = '\0';
                std::cout << "[" << inet_ntoa(remoteAddr.sin_addr) << ":" << remoteAddr.sin_port << "] -> " << recvBuffer << std::endl;
            }
        }
    }
    
    bool UDPClient::Send(std::string message)
    {
        int ret = sendto(udpSocket, message.c_str(), message.length(), 0, (sockaddr *)&remoteAddr, sizeof(remoteAddr));
        if (ret == SOCKET_ERROR)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    main.cpp

    #include 
    #include 
    #include 
    
    #include "UDPClient.h"
    #include "UDPServer.h"
    
    int main()
    {
        std::cout << "[0] -> UDPServer"
                  << "\n"
                  << "[1] -> UDPClient" << std::endl;
        u_int flag = 2;
        std::cin >> flag;
    
        switch (flag)
        {
        case 0:
        {
            std::cout << "[UDPServer] -> Start" << std::endl;
            UDPServer udpServer;
            udpServer.Bind(6789);
            std::thread recvThread(&UDPServer::Receive, &udpServer);
    
            // 主线程
            while (true)
            {
                std::cout << "\n[Input] -> ";
                std::string msg;
                std::cin >> msg;
                if (udpServer.Send(msg))
                {
                    std::cout << "[UDPServer] -> " << msg << std::endl;
                }
                else
                {
                    std::cout << "[ErrorCode] -> " << GetLastError() << std::endl;
                }
            }
    
            // 等待线程结束
            recvThread.join();
    
            std::cout << "[UDPServer] -> Stop" << std::endl;
            break;
        }
        case 1:
        {
            std::cout << "[UDPClient] -> Start" << std::endl;
            UDPClient udpClient;
            udpClient.Bind("127.0.0.1", 6789);
            std::thread recvThread(&UDPClient::Receive, &udpClient);
    
            // 主线程
            while (true)
            {
                std::cout << "\n[Input] -> ";
                std::string msg;
                std::cin >> msg;
                if (udpClient.Send(msg))
                {
                    std::cout << "[UDPClient] -> " << msg << std::endl;
                }
                else
                {
                    std::cout << "[ErrorCode] -> " << GetLastError() << std::endl;
                }
            }
    
            // 等待线程结束
            recvThread.join();
    
            std::cout << "[UDPClient] -> Stop" << std::endl;
            break;
        }
    
        default:
            break;
        }
    
        system("pause");
        return 0;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84

    CMakeLists.txt

    cmake_minimum_required(VERSION 3.0.0)
    project(UDPProtocol VERSION 0.1.0 LANGUAGES CXX)
    
    add_executable(${PROJECT_NAME} 
        UDPClient.cpp
        UDPServer.cpp
        main.cpp)
    
    if(WIN32)
        target_link_libraries(${PROJECT_NAME} PRIVATE ws2_32)
    endif()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    测试截图

  • 相关阅读:
    lamada List对象属性值转数组array
    二十、java版 SpringCloud分布式微服务云架构之Java 异常处理
    jsp三好学生评审管理系统Myeclipse开发mysql数据库web结构java编程计算机网页项目
    适用于在线学习的动态特征缩放方法
    k8s~istio的安装与核心组件
    Rust之Sea-orm快速入门指南
    Linux的redis启动过程详解
    Nginx.conf设置nginx优化(二)
    linux udp 广播recvfrom 返回 -1 错误码是 11 EAGAIN Resource temporarily unavailable
    java实现pdf转为word
  • 原文地址:https://blog.csdn.net/a924282761/article/details/133877426