mirror of
https://github.com/wpilibsuite/allwpilib
synced 2026-07-05 03:21:42 +00:00
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:
@@ -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;
|
||||
|
||||
@@ -56,6 +56,18 @@ class Tcp final : public NetworkStreamImpl<Tcp, uv_tcp_t> {
|
||||
return Create(*loop, flags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reuse this handle. This closes the handle, and after the close completes,
|
||||
* reinitializes it (identically to Create) and calls the provided callback.
|
||||
* Unlike Close(), it does NOT emit the closed signal, however, IsClosing()
|
||||
* will return true until the callback is called. This does nothing if
|
||||
* IsClosing() is true (e.g. if Close() was called).
|
||||
*
|
||||
* @param flags Flags
|
||||
* @param callback Callback
|
||||
*/
|
||||
void Reuse(std::function<void()> callback, unsigned int flags = AF_UNSPEC);
|
||||
|
||||
/**
|
||||
* Accept incoming connection.
|
||||
*
|
||||
@@ -304,6 +316,12 @@ class Tcp final : public NetworkStreamImpl<Tcp, uv_tcp_t> {
|
||||
|
||||
private:
|
||||
Tcp* DoAccept() override;
|
||||
|
||||
struct ReuseData {
|
||||
std::function<void()> callback;
|
||||
unsigned int flags;
|
||||
};
|
||||
std::unique_ptr<ReuseData> m_reuseData;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user