1.头文件声明
class UnixStreamSocket
{
public:
/* Struct for the data field of uv_req_t when writing data. */
struct UvWriteData
{
explicit UvWriteData(size_t storeSize)
{
this->store = new uint8_t[storeSize];
}
// Disable copy constructor because of the dynamically allocated data (store).
UvWriteData(const UvWriteData&) = delete;
~UvWriteData()
{
delete[] this->store;
}
uv_write_t req;
uint8_t* store{ nullptr };
};
enum class Role
{
PRODUCER = 1,
CONSUMER
};
public:
// 打开绑定管道,对应消费者,还绑定接收数据的函数
UnixStreamSocket(int fd, size_t bufferSize, UnixStreamSocket::Role role);
UnixStreamSocket& operator=(const UnixStreamSocket&) = delete;
UnixStreamSocket(const UnixStreamSocket&) = delete;
virtual ~UnixStreamSocket();
public:
// 关闭管道
void Close();
bool IsClosed() const
{
return this->closed;
}
// 数据写入管道 ,没有返回值值,需要添加返回值
void Write(const uint8_t* data, size_t len);
void Write(const std::string& data)
{
Write(reinterpret_cast<const uint8_t*>(data.c_str()), data.size());
}
/* Callbacks fired by UV events. */
public:
// libyuv 有数据到来,需要申请内存,用于读数据
void OnUvReadAlloc(size_t suggestedSize, uv_buf_t* buf);
// 返回读到的数据,最后调用UserOnUnixStreamRead通知子类需要读数据
void OnUvRead(ssize_t nread, const uv_buf_t* buf);
void OnUvWriteError(int error);
/* Pure virtual methods that must be implemented by the subclass. */
protected:
// 子类实现,数据读取完毕,放入buffer缓存中
virtual void UserOnUnixStreamRead() = 0;
// 子类实现,数据读取完毕 1.读数据错误调用 2.写数据错误调用
virtual void UserOnUnixStreamSocketClosed() = 0;
private:
// Allocated by this.
uv_pipe_t* uvHandle{ nullptr };
// Others.
bool closed{ false };
bool isClosedByPeer{ false };
bool hasError{ false };
protected:
// Passed by argument.
size_t bufferSize{ 0u };
UnixStreamSocket::Role role;
// Allocated by this.
uint8_t* buffer{ nullptr };
// Others.
size_t bufferDataLen{ 0u };
};
#endif
此类无法单独实例化,被ProducerSocket和ConsumerSocket 继承。