windows c语言 udp
时间: 2023-07-26 14:13:55 浏览: 129
以下是一个简单的 Windows C 语言 UDP 服务器和客户端示例:
服务器端:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib") // 链接 winsock 库
int main() {
WSADATA wsaData;
SOCKET serverSocket, clientSocket;
struct sockaddr_in serverAddr, clientAddr;
int clientAddrLen = sizeof(clientAddr);
char buffer[1024];
// 初始化 winsock 库
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("初始化 winsock 失败!\n");
return 1;
}
// 创建 UDP 套接字
if ((serverSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) {
printf("创建套接字失败!\n");
WSACleanup();
return 1;
}
// 绑定地址和端口
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(8888);
if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
printf("绑定地址和端口失败!\n");
closesocket(serverSocket);
WSACleanup();
return 1;
}
printf("服务器已启动,等待客户端连接...\n");
// 接收数据并回复客户端
while (1) {
memset(buffer, 0, sizeof(buffer));
if (recvfrom(serverSocket, buffer, sizeof(buffer), 0, (struct sockaddr*)&clientAddr, &clientAddrLen) == SOCKET_ERROR) {
printf("接收数据失败!\n");
break;
}
printf("客户端 %s:%d 发来消息:%s\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), buffer);
if (sendto(serverSocket, buffer, strlen(buffer), 0, (struct sockaddr*)&clientAddr, clientAddrLen) == SOCKET_ERROR) {
printf("回复客户端失败!\n");
break;
}
}
closesocket(serverSocket);
WSACleanup();
return 0;
}
```
客户端:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib") // 链接 winsock 库
int main() {
WSADATA wsaData;
SOCKET clientSocket;
struct sockaddr_in serverAddr;
char buffer[1024];
// 初始化 winsock 库
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("初始化 winsock 失败!\n");
return 1;
}
// 创建 UDP 套接字
if ((clientSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) {
printf("创建套接字失败!\n");
WSACleanup();
return 1;
}
// 设置服务器地址和端口
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
serverAddr.sin_port = htons(8888);
// 发送数据并接收回复
while (1) {
printf("请输入消息(输入 q 退出):\n");
fgets(buffer, sizeof(buffer), stdin);
if (strcmp(buffer, "q\n") == 0) {
break;
}
if (sendto(clientSocket, buffer, strlen(buffer), 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
printf("发送数据失败!\n");
break;
}
memset(buffer, 0, sizeof(buffer));
if (recvfrom(clientSocket, buffer, sizeof(buffer), 0, NULL, NULL) == SOCKET_ERROR) {
printf("接收回复失败!\n");
break;
}
printf("服务器回复:%s\n", buffer);
}
closesocket(clientSocket);
WSACleanup();
return 0;
}
```
注意:需要在 Visual Studio 中设置项目属性,将字符集设置为“使用多字节字符集”,否则中文会出现乱码。
阅读全文