1.cmakelist.txt
cmake_minimum_required(VERSION 3.16)
project(c_udp_server LANGUAGES C)
add_executable(c_udp_server main.c)
# link_directories("D:/Environment/mingw64/x86_64-w64-mingw32/lib")
target_link_libraries(c_udp_server wsock32)
include(GNUInstallDirs)
install(TARGETS c_udp_server
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() {
printf("server start---\n");
WSADATA wsaData;
int server_socket;
struct sockaddr_in server_addr, client_addr;
int client_addr_len = sizeof(client_addr);
char buffer[BUFFER_SIZE];
// 初始化Winsock库
if (WSAStartup(MAKEWORD(2, 2), &wsaData)!= 0) {
perror("WSAStartup failed");
return 1;
}
// 创建UDP套接字
if ((server_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 = INADDR_ANY;
// 绑定套接字到指定地址和端口
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
perror("Bind failed");
closesocket(server_socket);
WSACleanup();
return 1;
}
printf("Server is waiting for incoming messages...\n");
while (1) {
// 接收来自客户端的数据
int recv_len = recvfrom(server_socket, buffer, BUFFER_SIZE - 1, 0,
(struct sockaddr *)&client_addr, &client_addr_len);
if (recv_len == SOCKET_ERROR) {
perror("Receive failed");
continue;
}
buffer[recv_len] = '\0';
printf("Received message from client: %s", buffer);
// 发送响应给客户端---执行实际操作数据处理
const char *response = "Message received successfully";
int send_len = sendto(server_socket, response, strlen(response), 0,
(struct sockaddr *)&client_addr, client_addr_len);
if (send_len == SOCKET_ERROR) {
perror("Send failed");
continue;
}
}
closesocket(server_socket);
WSACleanup();
return 0;
}
3.结果