From 4b9f5d97dd77d8940a8fef89cf7612826b3e7506 Mon Sep 17 00:00:00 2001 From: Mathew Date: Tue, 30 Apr 2024 13:10:10 +1000 Subject: [PATCH] try send within same event loop --- index.js | 37 +++++++++++++++++++++++++------------ src/raw.cc | 15 +++++++++++++-- 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/index.js b/index.js index 8cbfb46..f63a6c1 100644 --- a/index.js +++ b/index.js @@ -104,7 +104,7 @@ class Socket extends EventEmitter { this.wrap.send (req.buffer, req.offset, req.length, req.address, function (bytes) { req.afterCallback.call (me, null, bytes); - }); + }, false); } catch (error) { req.afterCallback.call (me, error, 0); } @@ -159,18 +159,31 @@ class Socket extends EventEmitter { return this; } - const req = { - buffer: buffer, - offset: offset, - length: length, - address: address, - afterCallback: afterCallback, - beforeCallback: beforeCallback - }; - this.requests.push (req); - - if (this.sendPaused) + const req = { buffer, offset, length, address, afterCallback, beforeCallback }; + + if (this.sendPaused) { + if (req.beforeCallback) + req.beforeCallback (); + + try { + let sent = this.wrap.send (req.buffer, req.offset, req.length, req.address, (bytes) => { + req.afterCallback.call (this, null, bytes); + }, true); + + if (sent) { + return this + } + } catch(error){ + req.afterCallback.call (this, error, 0); + return + } + + this.requests.push (req); + this.resumeSend (); + } else { + this.requests.push (req); + } return this; } diff --git a/src/raw.cc b/src/raw.cc index 4d29a38..909c290 100644 --- a/src/raw.cc +++ b/src/raw.cc @@ -786,9 +786,10 @@ NAN_METHOD(SocketWrap::Send) { uint32_t length; int rc; char *data; + bool try_send; - if (info.Length () < 5) { - Nan::ThrowError("Five arguments are required"); + if (info.Length () < 6) { + Nan::ThrowError("Six arguments are required"); return; } @@ -811,6 +812,11 @@ NAN_METHOD(SocketWrap::Send) { Nan::ThrowTypeError("Callback argument must be a function"); return; } + + if (! info[5]->IsBoolean ()) { + Nan::ThrowTypeError("Try argument must be a boolean"); + return; + } rc = socket->CreateSocket (); if (rc != 0) { @@ -821,6 +827,7 @@ NAN_METHOD(SocketWrap::Send) { buffer = info[0]->ToObject (context).ToLocalChecked(); offset = Nan::To(info[1]).ToLocalChecked()->Value(); length = Nan::To(info[2]).ToLocalChecked()->Value(); + try_send = info[5]->ToBoolean (isolate)->Value (); data = node::Buffer::Data (buffer) + offset; @@ -890,6 +897,10 @@ NAN_METHOD(SocketWrap::Send) { } if (rc == SOCKET_ERROR) { + if(try_send){ + info.GetReturnValue().Set(Nan::New(false)); + return; + } Nan::ThrowError(raw_strerror (SOCKET_ERRNO)); return; }