我有两个程序,一个是我编写的程序,可以作为管道服务器使用io完成端口。另一个不是我写的,而是开源的,它大量使用libuv进行异步处理。
现在我要编辑此程序以通过libuv添加管道功能并能够与服务器联系。
我可以使用uv_pipe_connect
连接到服务器,并且触发了连接回调,然后从uv_read_start
开始读取,该返回0(无错误),因此我期望一旦服务器写入,分配回调和读取回调就会被触发给客户。
但是,当服务器写入一些字节,并且我通过iocp接收到有关已写入一定数量字节的通知时,客户端不会收到任何信息,也不会调用任何回调。并且在关闭服务器进程时,将读取读取回调,并显示错误EOF
这是我正在使用的与libuv相关的代码:
class IPipeListener;
class PipeClient
{
public:
PipeClient(IPipeListener* listener, const std::string& pipe_name);
~PipeClient();
void stop();
private:
static void onAllocBuff(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf);
static void onConnect(uv_connect_t *connect_req, int result);
static void onRead(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf);
static void onWrite(uv_write_t* req, int result);
// a pod structure used to read and write data
PipeCommand command;
IPipeListener* m_listener = nullptr;
uv_pipe_t m_pipe;
uv_connect_t m_connect;
uv_read_t read_req;
uv_write_t write_req;
};
PipeClient::PipeClient(IPipeListener* listener, const std::string& pipe_name)
{
if (!listener || pipe_name.empty())
return;
m_listener = listener;
uv_pipe_init(uv_default_loop(), &m_pipe, 1);
m_connect.data = this;
write_req.data = this;
read_req.data = this;
uv_pipe_connect(&m_connect, &m_pipe, pipe_name.c_str(), onConnect);
}
void PipeClient::onAllocBuff(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf)
{
MessageBoxA(0, "onAllocBuff", "onAllocBuff", 0);
auto pipe = static_cast<PipeClient*>(handle->data);
buf->base = reinterpret_cast<char*>(&pipe->command);
buf->len = sizeof(pipe->command);
}
void PipeClient::onConnect(uv_connect_t* connect_req, int result)
{
MessageBoxA(0, "onConnect", "onConnect", 0);
auto pipe = static_cast<PipeClient*>(connect_req->data);
if (result < 0)
{
pipe->command.code = PipeCommand::OpCode::Error;
pipe->m_listener->onPipeCommand(pipe->command);
return;
}
MessageBoxA(0, "starting read", "notify", 0);
int r = uv_read_start(connect_req->handle, onAllocBuff, onRead);
if (r != 0)
{
std::string err_msg = "failed to start reading with error : ";
err_msg += uv_err_name(r);
MessageBoxA(0, err_msg.c_str(), "error", 0);
}
}
void PipeClient::onRead(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf)
{
MessageBoxA(0, "onRead", "onRead", 0);
auto pipe = static_cast<PipeClient*>(stream->data);
uv_read_stop(stream);
if (nread < 0)
{
std::string err_msg = "failed to read with error : ";
err_msg += uv_err_name(nread);
MessageBoxA(0, err_msg.c_str(), "error", 0);
pipe->command.code = PipeCommand::OpCode::Error;
pipe->m_listener->onPipeCommand(pipe->command);
return;
}
pipe->m_listener->onPipeCommand(pipe->command);
uv_buf_t write_buff;
write_buff.base = reinterpret_cast<char*>(&pipe->command);
write_buff.len = sizeof(pipe->command);
uv_write(&pipe->write_req,
stream, &write_buff, 1, onWrite);
}
我不得不在uv_pipe_init
中将ipc标志设置为0,并将m_pipe
的数据设置为指向我的PipeClient
类。
从这里开始:https://github.com/libuv/libuv/blob/v1.x/src/win/pipe.c
我发现如果设置了ipc标志,则管道读取写入不是普通的iocp读取写入,而是采用了我不想要的其他方法