Skip to content

Commit

Permalink
Merge pull request codypiersall#97 from deets/implement-non-blocking-…
Browse files Browse the repository at this point in the history
…send

Introduce block-argument to send
  • Loading branch information
codypiersall committed Apr 19, 2022
2 parents 785693c + dd4dbe1 commit 9dfc361
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -38,7 +38,7 @@ Building from the GitHub repo works as well, natch:
pip3 install -e .

(If you want to run tests, you also need to `pip3 install trio curio pytest pytest-asyncio pytest-trio pytest-curio`,
then just run `pytest`.)
then just run `pytest test`.)

pynng might work on the BSDs as well. Who knows!

Expand Down
19 changes: 16 additions & 3 deletions pynng/nng.py
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
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 9dfc361

Please sign in to comment.