Add Reuse function to uv::Tcp (#1208)

This allows reusing the Tcp object in cases when the connection errors out.
This commit is contained in:
Peter Johnson
2018-07-22 12:31:50 -07:00
committed by GitHub
parent 85118a023d
commit 739267d36d
2 changed files with 38 additions and 0 deletions

View File

@@ -25,6 +25,26 @@ std::shared_ptr<Tcp> Tcp::Create(Loop& loop, unsigned int flags) {
return h;
}
void Tcp::Reuse(std::function<void()> callback, unsigned int flags) {
if (!IsClosing()) {
m_reuseData = std::make_unique<ReuseData>();
m_reuseData->callback = callback;
m_reuseData->flags = flags;
uv_close(GetRawHandle(), [](uv_handle_t* handle) {
Tcp& h = *static_cast<Tcp*>(handle->data);
if (!h.m_reuseData) return; // just in case
auto data = std::move(h.m_reuseData);
int err =
uv_tcp_init_ex(h.GetLoopRef().GetRaw(), h.GetRaw(), data->flags);
if (err < 0) {
h.ReportError(err);
return;
}
data->callback();
});
}
}
std::shared_ptr<Tcp> Tcp::Accept() {
auto client = Create(GetLoopRef());
if (!client) return nullptr;