C++ TcpSocket自动工厂类
时间: 2024-05-04 11:17:44 浏览: 13
C++ TcpSocket自动工厂类的实现可以参考以下代码:
```cpp
#include <iostream>
#include <map>
#include <functional>
#include <memory>
#include <string>
#include <stdexcept>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
class TcpSocket {
public:
TcpSocket(int fd) : fd_(fd) { }
int fd() const { return fd_; }
~TcpSocket() {
if (fd_ != -1) {
close(fd_);
}
}
private:
int fd_;
};
class TcpServer {
public:
TcpServer() : fd_(socket(AF_INET, SOCK_STREAM, 0)) {
if (fd_ == -1) {
throw std::runtime_error("socket error");
}
}
void bind(const std::string& host, int port) {
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(host.c_str());
addr.sin_port = htons(port);
if (::bind(fd_, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == -1) {
throw std::runtime_error("bind error");
}
}
void listen() {
if (::listen(fd_, 128) == -1) {
throw std::runtime_error("listen error");
}
}
std::unique_ptr<TcpSocket> accept() {
int client_fd = ::accept(fd_, nullptr, nullptr);
if (client_fd == -1) {
throw std::runtime_error("accept error");
}
return std::make_unique<TcpSocket>(client_fd);
}
~TcpServer() {
if (fd_ != -1) {
close(fd_);
}
}
private:
int fd_;
};
class TcpSocketFactory {
public:
TcpSocketFactory() {
register_creator("tcp", []() {
return std::make_unique<TcpSocket>();
});
}
void register_creator(const std::string& protocol, std::function<std::unique_ptr<TcpSocket>()> creator) {
creators_[protocol] = std::move(creator);
}
std::unique_ptr<TcpSocket> create(const std::string& url) {
size_t pos = url.find("://");
if (pos == std::string::npos) {
throw std::runtime_error("invalid url");
}
std::string protocol = url.substr(0, pos);
auto it = creators_.find(protocol);
if (it == creators_.end()) {
throw std::runtime_error("unsupported protocol");
}
return it->second();
}
private:
std::map<std::string, std::function<std::unique_ptr<TcpSocket>()>> creators_;
};
int main() {
TcpSocketFactory factory;
// 注册TcpSocket的创建函数
factory.register_creator("tcp", []() {
return std::make_unique<TcpSocket>();
});
// 使用TcpSocketFactory创建TcpServer
TcpServer server;
server.bind("127.0.0.1", 12345);
server.listen();
while (true) {
std::unique_ptr<TcpSocket> client = server.accept();
std::string url = "tcp://127.0.0.1:12345"; // 假设这是客户端连接的url
std::unique_ptr<TcpSocket> socket = factory.create(url);
std::cout << "client connected" << std::endl;
}
return 0;
}
```
上述代码中,`TcpSocketFactory` 实现了一个自动工厂类,可以根据不同的协议创建不同的 `TcpSocket` 对象。在 `TcpSocketFactory` 中,我们使用 `std::map` 存储了不同协议对应的创建函数,然后在 `create` 方法中根据传入的 url 解析协议,调用对应的创建函数创建 `TcpSocket` 对象。
在 `main` 函数中,我们首先需要实例化一个 `TcpSocketFactory` 对象,并注册 `TcpSocket` 的创建函数。然后,我们创建了一个 `TcpServer` 对象,并调用 `accept` 方法接受客户端连接。在连接建立后,我们可以使用 `TcpSocketFactory` 创建新的 `TcpSocket` 对象来与客户端通信。