类封装socket实现tcp,udp的代码
时间: 2023-09-23 22:07:27 浏览: 105
下面是一个简单的示例代码,用C++封装了Socket类,实现了TCP和UDP协议的通信功能。
```c++
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
using namespace std;
class Socket {
public:
Socket(int type);
~Socket();
int Bind(const string& ip, unsigned short port);
int Listen(int backlog = 5);
int Accept(Socket& client);
int Connect(const string& ip, unsigned short port);
void Close();
int Send(const string& data);
int Recv(string& data);
private:
int _sockfd;
int _type;
};
Socket::Socket(int type): _type(type) {
if (type == SOCK_STREAM) {
_sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
} else if (type == SOCK_DGRAM) {
_sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
} else {
_sockfd = -1;
}
}
Socket::~Socket() {
Close();
}
int Socket::Bind(const string& ip, unsigned short port) {
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (ip.empty()) {
addr.sin_addr.s_addr = INADDR_ANY;
} else {
addr.sin_addr.s_addr = inet_addr(ip.c_str());
}
return bind(_sockfd, (sockaddr*)&addr, sizeof(addr));
}
int Socket::Listen(int backlog) {
return listen(_sockfd, backlog);
}
int Socket::Accept(Socket& client) {
sockaddr_in addr = {};
socklen_t addrlen = sizeof(addr);
int sockfd = accept(_sockfd, (sockaddr*)&addr, &addrlen);
if (sockfd < 0) {
return sockfd;
}
client._sockfd = sockfd;
client._type = _type;
return 0;
}
int Socket::Connect(const string& ip, unsigned short port) {
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip.c_str());
return connect(_sockfd, (sockaddr*)&addr, sizeof(addr));
}
void Socket::Close() {
if (_sockfd != -1) {
close(_sockfd);
_sockfd = -1;
}
}
int Socket::Send(const string& data) {
return send(_sockfd, data.c_str(), data.size(), 0);
}
int Socket::Recv(string& data) {
char buffer[1024] = {};
int n = recv(_sockfd, buffer, sizeof(buffer), 0);
if (n > 0) {
data = string(buffer, n);
}
return n;
}
int main() {
Socket server(SOCK_STREAM);
server.Bind("127.0.0.1", 8080);
server.Listen();
Socket client(SOCK_STREAM);
client.Connect("127.0.0.1", 8080);
Socket conn(SOCK_STREAM);
server.Accept(conn);
string message = "Hello, world!";
client.Send(message);
string buffer;
conn.Recv(buffer);
cout << buffer << endl;
return 0;
}
```
以上是一个简单的Socket类的实现,可以通过调用Socket类的方法,实现TCP和UDP协议的通信。其中,Bind方法用于绑定IP地址和端口号,Listen方法用于监听连接请求,Accept方法用于接受客户端连接,Connect方法用于连接到服务端,Send方法用于发送数据,Recv方法用于接收数据。
阅读全文