From e106e769cf887038d00eb11ed781ca24c12dffa4 Mon Sep 17 00:00:00 2001 From: Kiritow <1362050620@qq.com> Date: Thu, 7 Jun 2018 21:01:40 +0800 Subject: [PATCH] Add Helper functions --- gsock_helper.cpp | 87 ++++++++++++++++++++++++++++++++++++++++++++++++ gsock_helper.h | 26 +++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 gsock_helper.cpp create mode 100644 gsock_helper.h diff --git a/gsock_helper.cpp b/gsock_helper.cpp new file mode 100644 index 0000000..c8a3422 --- /dev/null +++ b/gsock_helper.cpp @@ -0,0 +1,87 @@ +#include "gsock_helper.h" + +sock_helper::sock_helper(sock& s) :_s(s) +{ + +} + +int sock_helper::sendall(const void* ptr, int datasz, int& bytes_sent) +{ + int done = 0; + while (done < datasz) + { + int ret = _s.send(((const char*)ptr) + done, datasz - done); + if (ret <= 0) + { + bytes_sent = done; + return ret; + } + done += ret; + } + bytes_sent = done; + return done; +} + +int sock_helper::sendall(const void* ptr, int datasz) +{ + int x; + return sendall(ptr, datasz, x); +} + +int sock_helper::recvuntil(void* buff, int max_length, + const std::function& cond_fn, int& bytes_recv) +{ + int done = 0; + while (done < max_length) + { + int ret = _s.recv(((char*)buff) + done, max_length - done); + if (ret <= 0) + { + bytes_recv = done; + return ret; + } + + if (cond_fn()) + { + return done; + } + } + bytes_recv = done; + return done; +} + +int sock_helper::recvuntil(void* buff, int max_length, + const std::function& cond_fn, int& bytes_recv) +{ + int done = 0; + while (done < max_length) + { + int ret = _s.recv(((char*)buff) + done, max_length - done); + if (ret <= 0) + { + bytes_recv = done; + return ret; + } + + if (cond_fn(buff, done)) + { + return done; + } + } + bytes_recv = done; + return done; +} + +int sock_helper::recvuntil(void* buff, int max_length, + const std::function& cond_fn) +{ + int x; + return recvuntil(buff, max_length, cond_fn, x); +} + +int sock_helper::recvuntil(void* buff, int max_length, + const std::function& cond_fn) +{ + int x; + return recvuntil(buff, max_length, cond_fn, x); +} \ No newline at end of file diff --git a/gsock_helper.h b/gsock_helper.h new file mode 100644 index 0000000..7605b72 --- /dev/null +++ b/gsock_helper.h @@ -0,0 +1,26 @@ +/** General Socket Wrapper +* Created By Kiritow. (https://github.com/kiritow) +* Licensed under MIT +*/ + +// GSock Helper + +#pragma once +#include "gsock.h" +#include + +class sock_helper +{ +public: + sock_helper(sock&); + + int sendall(const void* ptr, int datasz); + int sendall(const void* ptr, int datasz, int& bytes_sent); + + int recvuntil(void* buff, int max_length, const std::function& cond_fn); + int recvuntil(void* buff, int max_length, const std::function& cond_fn, int& bytes_recv); + int recvuntil(void* buff, int max_length, const std::function& cond_fn); + int recvuntil(void* buff, int max_length, const std::function& cond_fn, int& bytes_recv); +private: + sock & _s; +}; \ No newline at end of file