使用C++封装TCP客户端类,实现在网络不够稳定的情况下讲字符串可靠传输服务端
时间: 2024-04-10 12:33:33 浏览: 177
你可以使用C++封装一个TCP客户端类来实现在网络不稳定的情况下可靠地传输字符串给服务端。下面是一个简单的示例代码:
```cpp
#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
class TCPClient {
private:
int sock;
std::string address;
int port;
struct sockaddr_in server;
public:
TCPClient(std::string address, int port) {
this->address = address;
this->port = port;
// 创建套接字
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
std::cerr << "Failed to create socket." << std::endl;
exit(1);
}
std::cout << "Socket created." << std::endl;
server.sin_addr.s_addr = inet_addr(address.c_str());
server.sin_family = AF_INET;
server.sin_port = htons(port);
}
bool connectToServer() {
// 连接到服务器
if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
std::cerr << "Failed to connect to server." << std::endl;
return false;
}
std::cout << "Connected to server." << std::endl;
return true;
}
bool sendString(std::string data) {
// 发送字符串给服务器
if (send(sock, data.c_str(), strlen(data.c_str()), 0) < 0) {
std::cerr << "Failed to send data to server." << std::endl;
return false;
}
return true;
}
void closeConnection() {
// 关闭连接
close(sock);
}
};
int main() {
std::string serverAddress = "127.0.0.1";
int serverPort = 12345;
TCPClient client(serverAddress, serverPort);
if (client.connectToServer()) {
std::string message = "Hello, server!";
if (client.sendString(message)) {
std::cout << "Message sent successfully." << std::endl;
}
client.closeConnection();
}
return 0;
}
```
这是一个简单的TCP客户端类,通过封装socket和相关的网络操作函数,可以实现与服务端的连接和数据传输。你可以在`main`函数中实例化一个`TCPClient`对象,指定服务器的地址和端口。然后调用`connectToServer`函数连接到服务器,调用`sendString`函数发送字符串给服务器,最后调用`closeConnection`函数关闭连接。
当网络不稳定时,TCP协议会自动处理数据的可靠传输,你不需要做额外的处理。如果连接中断,TCP会自动尝试重新建立连接,并继续传输之前未完全传输的数据。
请注意,这只是一个简单的示例代码,你可能需要根据实际需求进行修改和扩展。例如,你可能需要处理接收来自服务端的响应,添加错误处理等功能。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)