diff options
author | Petteri Aimonen <jpa@git.mail.kapsi.fi> | 2013-09-13 12:59:31 +0300 |
---|---|---|
committer | Petteri Aimonen <jpa@git.mail.kapsi.fi> | 2013-09-13 12:59:31 +0300 |
commit | f47410ea4b8ae43e19facd378be4cf1073e1813b (patch) | |
tree | 53fdc4bac6615f07e830d7d538c90abbea1ead4b /examples/network_server/common.c | |
parent | fd9a79a06db00c6199a5dcaee22ed2cd8e3c3e9b (diff) |
Move examples into subfolders, add READMEs
Diffstat (limited to 'examples/network_server/common.c')
-rw-r--r-- | examples/network_server/common.c | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/examples/network_server/common.c b/examples/network_server/common.c new file mode 100644 index 00000000..04a5aa85 --- /dev/null +++ b/examples/network_server/common.c @@ -0,0 +1,40 @@ +/* Simple binding of nanopb streams to TCP sockets. + */ + +#include <sys/socket.h> +#include <sys/types.h> +#include <pb_encode.h> +#include <pb_decode.h> + +#include "common.h" + +static bool write_callback(pb_ostream_t *stream, const uint8_t *buf, size_t count) +{ + int fd = (intptr_t)stream->state; + return send(fd, buf, count, 0) == count; +} + +static bool read_callback(pb_istream_t *stream, uint8_t *buf, size_t count) +{ + int fd = (intptr_t)stream->state; + int result; + + result = recv(fd, buf, count, MSG_WAITALL); + + if (result == 0) + stream->bytes_left = 0; /* EOF */ + + return result == count; +} + +pb_ostream_t pb_ostream_from_socket(int fd) +{ + pb_ostream_t stream = {&write_callback, (void*)(intptr_t)fd, SIZE_MAX, 0}; + return stream; +} + +pb_istream_t pb_istream_from_socket(int fd) +{ + pb_istream_t stream = {&read_callback, (void*)(intptr_t)fd, SIZE_MAX}; + return stream; +} |