VS2019:基于UDP协议的回声服务器

编译环境:Windows ,VS2019

UDP_Server.cpp

#include 
#include 
#pragma comment (lib, "ws2_32.lib")  //加载 ws2_32.dll
#pragma warning(disable : 4996)

#define BUF_SIZE 100

int main() {
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    //创建套接字,SOCK_DGRAM指明使用 UDP 协议
    SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);

    //绑定套接字
    sockaddr_in servAddr;
    memset(&servAddr, 0, sizeof(servAddr));  //每个字节都用0填充
    servAddr.sin_family = PF_INET;  //使用IPv4地址
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY); //自动获取IP地址
    servAddr.sin_port = htons(8000);  //端口
    bind(sock, (SOCKADDR*)&servAddr, sizeof(SOCKADDR));

    //接收客户端请求
    SOCKADDR cliAddr;  //客户端地址信息
    int nSize = sizeof(SOCKADDR);
    char buff[BUF_SIZE];  //缓冲区
    while (1) {
        int strLen = recvfrom(sock, buff, BUF_SIZE, 0, &cliAddr, &nSize);
        sendto(sock, buff, strLen, 0, &cliAddr, nSize);
    }

    closesocket(sock);
    WSACleanup();
    return 0;
}

UDP_Client.cpp

#include 
#include 
#pragma comment(lib, "ws2_32.lib")  //加载 ws2_32.dll
#pragma warning(disable : 4996)

#define BUF_SIZE 100

int main() {
    //初始化DLL
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    //创建套接字
    SOCKET sock = socket(PF_INET, SOCK_DGRAM, 0);

    //服务器地址信息
    sockaddr_in servAddr;
    memset(&servAddr, 0, sizeof(servAddr));  //每个字节都用0填充
    servAddr.sin_family = PF_INET;
    servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    servAddr.sin_port = htons(8000);

    //不断获取用户输入并发送给服务器,然后接受服务器数据
    sockaddr fromAddr;
    int addrLen = sizeof(fromAddr);
    while (1) 
    {
        char buff[BUF_SIZE] = { 0 };
        printf("Input a string: ");
        gets_s(buff);
        sendto(sock, buff, strlen(buff), 0, (struct sockaddr*) & servAddr, sizeof(servAddr));
        int strLen = recvfrom(sock, buff, BUF_SIZE, 0, &fromAddr, &addrLen);
        buff[strLen] = 0;
        printf("Message from server: %s\n", buff);
    }

    closesocket(sock);
    WSACleanup();
    return 0;
}

运行截图:
VS2019:基于UDP协议的回声服务器_第1张图片

你可能感兴趣的:(C++,socket通信)