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.结果

相关推荐
Sylvia-girl2 小时前
Java——抽象类
java·开发语言
Yana.nice4 小时前
Bash函数详解
开发语言·chrome·bash
tomorrow.hello5 小时前
Java并发测试工具
java·开发语言·测试工具
晓13136 小时前
JavaScript加强篇——第四章 日期对象与DOM节点(基础)
开发语言·前端·javascript
老胖闲聊6 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
阿维的博客日记7 小时前
TCP和UDP区别
tcp/ip·udp·php
她说人狗殊途7 小时前
java.net.InetAddress
java·开发语言
天使day7 小时前
Cursor的使用
java·开发语言·ai
wanhengidc7 小时前
UDP服务器的优缺点都包含哪些?
服务器·网络协议·udp
Dxy12393102167 小时前
Python ExcelWriter详解:从基础到高级的完整指南
开发语言·python