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