给出在windows下用C语言实现客户端和服务端进行udp通信的示例代码
时间: 2024-02-25 11:56:20 浏览: 150
以下是在Windows下用C语言实现UDP通信的示例代码:
服务端代码:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WSADATA wsaData;
SOCKET serverSocket;
SOCKADDR_IN serverAddr, clientAddr;
int clientAddrLen = sizeof(clientAddr);
char buffer[1024];
int recvLen;
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
printf("WSAStartup failed.\n");
return 1;
}
// 创建socket
serverSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (serverSocket == INVALID_SOCKET)
{
printf("Socket creation failed.\n");
WSACleanup();
return 1;
}
// 绑定地址和端口
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(12345);
if (bind(serverSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
{
printf("Bind failed.\n");
closesocket(serverSocket);
WSACleanup();
return 1;
}
printf("Server is listening on port 12345...\n");
// 接收数据
while (1)
{
recvLen = recvfrom(serverSocket, buffer, sizeof(buffer), 0, (SOCKADDR*)&clientAddr, &clientAddrLen);
if (recvLen == SOCKET_ERROR)
{
printf("Receive failed.\n");
break;
}
printf("Received message from %s:%d\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
buffer[recvLen] = '\0';
printf("Message content: %s\n", buffer);
// 回复客户端
if (sendto(serverSocket, buffer, recvLen, 0, (SOCKADDR*)&clientAddr, sizeof(clientAddr)) == SOCKET_ERROR)
{
printf("Send failed.\n");
break;
}
}
// 关闭socket和Winsock
closesocket(serverSocket);
WSACleanup();
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WSADATA wsaData;
SOCKET clientSocket;
SOCKADDR_IN serverAddr;
char buffer[1024];
int recvLen;
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
printf("WSAStartup failed.\n");
return 1;
}
// 创建socket
clientSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (clientSocket == INVALID_SOCKET)
{
printf("Socket creation failed.\n");
WSACleanup();
return 1;
}
// 设置服务端地址和端口
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
serverAddr.sin_port = htons(12345);
// 发送数据
strcpy(buffer, "Hello, server!");
if (sendto(clientSocket, buffer, strlen(buffer), 0, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
{
printf("Send failed.\n");
closesocket(clientSocket);
WSACleanup();
return 1;
}
printf("Sent message: %s\n", buffer);
// 接收回复
recvLen = recvfrom(clientSocket, buffer, sizeof(buffer), 0, NULL, NULL);
if (recvLen == SOCKET_ERROR)
{
printf("Receive failed.\n");
closesocket(clientSocket);
WSACleanup();
return 1;
}
buffer[recvLen] = '\0';
printf("Received message: %s\n", buffer);
// 关闭socket和Winsock
closesocket(clientSocket);
WSACleanup();
return 0;
}
```
其中,服务端监听的端口为12345,客户端连接的地址为127.0.0.1,端口为12345。你可以根据需要修改这些参数。
阅读全文