使用c++语言编写简单UDP通信程序。通信过程描述如下: (1)UDP客户端向UDP服务端发送消息:“你好!欢迎对话”;服务端收到后在屏幕上打印出信息并立即向客户端回应消息:“谢谢!”;客户端收到后在屏幕上打印。
时间: 2024-10-06 18:06:30 浏览: 30
在C++中,使用UDP(用户数据报协议)进行简单的点对点通信,你可以按照以下步骤编写程序:
首先,我们需要包含必要的头文件,并创建一个`UDPSocket`类来处理套接字操作:
```cpp
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
class UDPSocket {
public:
UDPSocket(int port) : socket_(socket(AF_INET, SOCK_DGRAM, 0)) {
if (socket_ == -1) {
perror("Error creating socket");
exit(1);
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on any interface
if (bind(socket_, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("Error binding socket");
exit(1);
}
}
~UDPSocket() {
close(socket_);
}
void sendMessage(const std::string& message, const std::string& recipient_ip, int recipient_port) {
struct sockaddr_in client_addr;
socklen_t addr_len = sizeof(client_addr);
if (sendto(socket_, message.c_str(), message.size(), 0, (struct sockaddr*)&client_addr, addr_len) == -1) {
perror("Error sending message");
} else {
printf("Message sent to %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
}
}
private:
int socket_;
};
```
接下来,创建客户端和服务器端的示例函数:
```cpp
void sendHelloClient(UDPSocket& client, const std::string& server_ip, int server_port) {
std::string message = "你好!欢迎对话";
client.sendMessage(message, server_ip, server_port);
}
void handleRequestServer(UDPSocket& server, const std::string& response_message) {
std::cout << "Received: " << response_message << "\n";
server.sendMessage("谢谢!", server.getAddress().c_str(), server.getPort());
}
int main() {
UDPSocket server(8080);
std::string server_ip = "127.0.0.1"; // Use your own IP or loopback address for testing
sendHelloClient(server, server_ip, server.getPort());
char buffer[256];
while (true) {
ssize_t bytes_received = recvfrom(server.socket_, buffer, sizeof(buffer), 0, nullptr, nullptr);
if (bytes_received > 0) {
handleRequestServer(server, std::string(buffer, bytes_received));
} else if (bytes_received == 0) {
break; // Connection closed by peer
} else {
perror("Error receiving data");
}
}
return 0;
}
```
这个例子中,`main`函数启动了一个服务器,监听8080端口。当客户端发送"你好!欢迎对话"时,服务器会接收并回应"谢谢!"。注意,这只是一个基本的示例,实际应用中你可能需要添加错误检查、异常处理以及适当的线程管理。
阅读全文