C++封装TcpSocket类
时间: 2024-01-16 10:05:26 浏览: 61
好的,下面是一个简单的封装TcpSocket类的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAX_BUFFER_SIZE 1024
class TcpSocket {
private:
int sockfd;
struct sockaddr_in server_addr;
public:
TcpSocket() {
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
memset(&server_addr, 0, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
}
~TcpSocket() {
close(sockfd);
}
bool connect(const char* server_ip, uint16_t server_port) {
server_addr.sin_addr.s_addr = inet_addr(server_ip);
server_addr.sin_port = htons(server_port);
int ret = ::connect(sockfd, (struct sockaddr*)&server_addr, sizeof(struct sockaddr_in));
if (ret == -1) {
perror("connect");
return false;
}
return true;
}
bool send(const char* data, size_t len) {
size_t total_sent = 0;
while (total_sent < len) {
ssize_t sent = ::send(sockfd, data + total_sent, len - total_sent, 0);
if (sent == -1) {
perror("send");
return false;
}
total_sent += sent;
}
return true;
}
bool recv(char* buffer, size_t len, size_t& recv_len) {
memset(buffer, 0, len);
ssize_t recv = ::recv(sockfd, buffer, len, 0);
if (recv == -1) {
perror("recv");
return false;
}
recv_len = recv;
return true;
}
};
```
这个类封装了一个基本的TcpSocket连接,包括创建socket、连接服务器、发送数据和接收数据等操作。其中,connect函数用于连接服务器,send函数用于发送数据,recv函数用于接收数据。注意,在send和recv函数中,由于网络传输可能会出现分包的情况,因此需要循环发送和接收数据,直到数据完整传输或接收完毕为止。
阅读全文