Skip to content

Commit

Permalink
Introduce block-argument to send
Browse files Browse the repository at this point in the history
By default, sending blocks. When block=False, raise pynng.TryAgain
if no data could be delivered.
  • Loading branch information
deets authored and liu-kan committed Aug 21, 2022
1 parent 785693c commit 3a3dfe4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
19 changes: 16 additions & 3 deletions pynng/nng.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,10 +456,23 @@ def recv(self, block=True):
lib.nng_free(data[0], size_t[0])
return recvd

def send(self, data):
"""Sends ``data`` (either ``bytes`` or ``bytearray``) on socket."""
def send(self, data, block=True):
"""Sends ``data`` on socket.
Args:
data: either ``bytes`` or ``bytearray``
block: If block is True (the default), the function will
not return until the operation is completed or times out.
If block is False, the function will raise ``pynng.TryAgain``
immediately if no data was sent.
"""
_ensure_can_send(data)
err = lib.nng_send(self.socket, data, len(data), 0)
flags = 0
if not block:
flags |= lib.NNG_FLAG_NONBLOCK
err = lib.nng_send(self.socket, data, len(data), flags)
check_err(err)

async def arecv(self):
Expand Down
6 changes: 6 additions & 0 deletions test/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ def test_nonblocking_recv_works():
s.recv(block=False)


def test_nonblocking_send_works():
with pynng.Pair0(listen=addr) as s:
with pytest.raises(pynng.TryAgain):
s.send(b'sad message, never will be seen', block=False)


@pytest.mark.trio
async def test_context():
with pynng.Req0(listen=addr, recv_timeout=1000) as req_sock, \
Expand Down

0 comments on commit 3a3dfe4

Please sign in to comment.