c++ udp服务端和客户端设置
时间: 2024-11-27 18:12:32 浏览: 0
在C++中创建UDP(用户数据报协议)服务器和客户端通常涉及以下几个步骤:
**UDP服务器设置**:
1. **包含头文件**:
```cpp
#include <iostream>
#include <string>
#include <sys/socket.h> // 对于socket操作
#include <arpa/inet.h> // 对于地址解析
```
2. **创建套接字**:
```cpp
int server_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (server_socket == -1) {
perror("Failed to create socket");
exit(1);
}
```
3. **绑定IP和端口**:
```cpp
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERV_PORT); // 端口号
inet_pton(AF_INET, "localhost", &server_addr.sin_addr); // 设置本地IP(这里通常是"localhost")
if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("Failed to bind");
close(server_socket);
exit(1);
}
```
4. **接收数据循环**:
```cpp
char buffer[BUFSIZ];
while (true) {
socklen_t len = sizeof(server_addr);
ssize_t bytes_received = recvfrom(server_socket, buffer, BUFSIZ, 0, (struct sockaddr*)&client_addr, &len);
if (bytes_received > 0) {
std::cout << "Received message from " << inet_ntoa(client_addr.sin_addr) << ":" << ntohs(client_addr.sin_port) << ": " << buffer << "\n";
} else {
perror("recvfrom failed");
}
}
```
**UDP客户端设置**:
1. **包含头文件**:
同上
2. **创建套接字**:
```cpp
int client_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (client_socket == -1) {
perror("Failed to create socket");
exit(1);
}
```
3. **设置发送信息**:
```cpp
const char* message = "Hello, Server!";
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET, "localhost", &server_addr.sin_addr);
sendto(client_socket, message, strlen(message), 0, (struct sockaddr*)&server_addr, sizeof(server_addr));
```
4. **关闭套接字**:
```cpp
close(client_socket);
```
阅读全文