muduo 客户端 C++11 改写
时间: 2024-01-16 17:03:44 浏览: 76
根据提供的引用内容,以下是一个使用C++11改写的muduo客户端的示例:
```cpp
#include <iostream>
#include <string>
#include <memory>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main() {
// 创建socket
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
std::cerr << "Failed to create socket." << std::endl;
return -1;
}
// 设置服务器地址
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8888);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
// 连接服务器
if (connect(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) {
std::cerr << "Failed to connect to server." << std::endl;
close(sockfd);
return -1;
}
// 发送数据
std::string message = "Hello, server!";
if (send(sockfd, message.c_str(), message.size(), 0) == -1) {
std::cerr << "Failed to send data." << std::endl;
close(sockfd);
return -1;
}
// 接收数据
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
if (recv(sockfd, buffer, sizeof(buffer), 0) == -1) {
std::cerr << "Failed to receive data." << std::endl;
close(sockfd);
return -1;
}
// 输出接收到的数据
std::cout << "Received data: " << buffer << std::endl;
// 关闭socket
close(sockfd);
return 0;
}
```
该示例使用了C++11的一些新特性,如智能指针和字符串字面量。它创建了一个TCP socket,并连接到指定的服务器地址。然后发送一条消息给服务器,并接收服务器返回的数据。最后关闭socket。
阅读全文