Cmakelist.txt之win-c-udp-client

1.cmakelist.txt

复制代码
cmake_minimum_required(VERSION 3.16)
​
project(c_udp_client LANGUAGES C)
​
add_executable(c_udp_client main.c)
​
target_link_libraries(c_udp_client wsock32)
​
​
include(GNUInstallDirs)
install(TARGETS c_udp_client
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
​

2.测试代码

复制代码
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>
​
// #pragma comment(lib, "ws2_32.lib")
​
#define PORT 8888
#define BUFFER_SIZE 1024
​
int main() {
    WSADATA wsaData;
    int client_socket;
    struct sockaddr_in server_addr;
    char buffer[BUFFER_SIZE];
​
    // 初始化Winsock库
    if (WSAStartup(MAKEWORD(2, 2), &wsaData)!= 0) {
        perror("WSAStartup failed");
        return 1;
    }
​
    // 创建UDP套接字
    if ((client_socket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
        perror("Socket creation failed");
        WSACleanup();
        return 1;
    }
​
    // 初始化服务器地址结构
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
​
    while (1) {
        printf("\nEnter a message to send to the server: ");
        fgets(buffer, BUFFER_SIZE, stdin);
​
        // 发送数据到服务器
        int send_len = sendto(client_socket, buffer, strlen(buffer), 0,
                              (struct sockaddr *)&server_addr, sizeof(server_addr));
        if (send_len == SOCKET_ERROR) {
            perror("Send failed");
            WSACleanup();
            return 1;
        }
​
        // 接收服务器的响应
        int recv_len = recvfrom(client_socket, buffer, BUFFER_SIZE - 1, 0, NULL, NULL);
        if (recv_len == SOCKET_ERROR) {
            perror("Receive failed");
            WSACleanup();
            return 1;
        }
        buffer[recv_len] = '\0';
​
        printf("Server response: %s", buffer);
    }
​
​
    closesocket(client_socket);
    WSACleanup();
    return 0;
}
​
复制代码
​

3.结果

相关推荐
wuminyu19 小时前
JVM规范学习总结:解释器与JIT编译器如何处理JVM字节码
java·linux·c语言·jvm·c++
小徐不徐说20 小时前
序列化与反序列化:把 C++ 对象可靠地保存下来
开发语言·数据库·c++·php
ragnwang20 小时前
Notes: Python pybind11 import C++ module
开发语言·c++·python
Wang's Blog20 小时前
Java 项目实战: 交友项目 - 搜索附近的功能概述和分析
java·开发语言·交友
骑着蜗牛撵大象32720 小时前
大模型 Agent 的沙箱护栏:gVisor 隔离、出口白名单与审计闭环
java·开发语言·jvm·安全·agent沙箱·gvisor·microvm
Dxy123931021621 小时前
JS DES 加密详解
开发语言·javascript·arcgis
充值内卷21 小时前
我给桌面加了个鱼缸:C++ 写后端,WebView2 里养一座 Three.js 小岛
开发语言·javascript·c++
云和数据.ChenGuang1 天前
深入解析 Python 的 dir():从用法到 CPython 源码实现
开发语言·人工智能·python·langchain
nice_lcj5201 天前
深入理解 Java 反射:从 Class 对象到方法调用(含性能实测 + 迷你 IOC 实战 + 面试考点)
java·开发语言·后端·面试
樱花树下的数学喵1 天前
手写简易 STL string|C++ 字符串底层实现
开发语言·c++