asio2
asio2 copied to clipboard
教主是否可以给asio2增加对管道和unix域套接字的支持呢
asio本身是支持的
#include <iostream>
#include <string>
#include <asio.hpp>
#ifdef _WIN32
const char* PIPE_NAME = "\\\\.\\pipe\\mypipe";
#else
const char* PIPE_NAME = "/tmp/mypipe";
#endif
class PipeServer {
public:
PipeServer(asio::io_context& io_context)
: pipe_(io_context)
{
#ifdef _WIN32
pipe_ = asio::windows::stream_handle(io_context, CreateNamedPipe(
PIPE_NAME, PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
1, 65536, 65536, 0, NULL));
#else
unlink(PIPE_NAME);
local::stream_protocol::endpoint ep(PIPE_NAME);
acceptor_ = asio::local::stream_protocol::acceptor(io_context, ep);
acceptor_.accept(pipe_);
#endif
std::cout << "Server: Pipe created." << std::endl;
}
void write(const std::string& message) {
asio::async_write(pipe_, asio::buffer(message),
[this](std::error_code ec, std::size_t /*length*/) {
if (!ec) {
std::cout << "Server: Write completed." << std::endl;
} else {
std::cerr << "Server: Write error: " << ec.message() << std::endl;
}
});
}
void read() {
asio::async_read(pipe_, asio::buffer(data_, max_length),
[this](std::error_code ec, std::size_t length) {
if (!ec) {
std::cout << "Server: Read " << length << " bytes: ";
std::cout.write(data_, length);
std::cout << std::endl;
} else {
std::cerr << "Server: Read error: " << ec.message() << std::endl;
}
});
}
private:
#ifdef _WIN32
asio::windows::stream_handle pipe_;
#else
asio::local::stream_protocol::acceptor acceptor_;
asio::local::stream_protocol::socket pipe_;
#endif
enum { max_length = 1024 };
char data_[max_length];
};
int main() {
try {
asio::io_context io_context;
PipeServer server(io_context);
server.write("Hello from server!");
server.read();
io_context.run();
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
这个框架不再添加新功能了。
我建议你用协程写,直接自己写,很简单,没多少代码。