feat(socket): Utility function peek()

This commit is contained in:
Michael Carlberg 2016-12-14 07:13:07 +01:00
parent 4606c41577
commit 7822f912aa
2 changed files with 16 additions and 5 deletions

View File

@ -19,7 +19,9 @@ namespace socket_util {
ssize_t send(const void* data, size_t len, int flags = 0);
ssize_t send(const string& data, int flags = 0);
string receive(const ssize_t receive_bytes, ssize_t& bytes_received_addr, int flags = 0);
string receive(const ssize_t receive_bytes, ssize_t* bytes_received, int flags = 0);
bool peek(const size_t peek_bytes);
bool poll(short int events = POLLIN, int timeout_ms = -1);
protected:

View File

@ -72,18 +72,27 @@ namespace socket_util {
/**
* Receive data
*/
string unix_connection::receive(const ssize_t receive_bytes, ssize_t& bytes_received_addr, int flags) {
string unix_connection::receive(const ssize_t receive_bytes, ssize_t* bytes_received, int flags) {
char buffer[BUFSIZ];
bytes_received_addr = ::recv(m_fd, buffer, receive_bytes, flags);
if (bytes_received_addr == -1) {
if ((*bytes_received = ::recv(m_fd, buffer, receive_bytes, flags)) == -1) {
throw system_error("Failed to receive data");
} else {
buffer[*bytes_received] = 0;
}
buffer[bytes_received_addr] = 0;
return string{buffer};
}
/**
* Peek at the specified number of bytes
*/
bool unix_connection::peek(const size_t peek_bytes) {
ssize_t bytes_seen{0};
receive(peek_bytes, &bytes_seen, MSG_PEEK);
return bytes_seen > 0;
}
/**
* Poll file descriptor for to check for available data
*/