simple-socket library 1.2.0
TCPSocket.cpp
Go to the documentation of this file.
1#include "TCPSocket.h"
2#include "TempFailure.h"
3
4#include <sys/socket.h>
5#include <netinet/in.h>
6#include <poll.h>
7
8using namespace NET;
9
11: InternetSocket( STREAM, IPPROTO_TCP)
12{}
13
15: InternetSocket( handle.release() )
16{}
17
18int TCPSocket::sendAll( const void* buffer, size_t len)
19{
20 size_t sent = 0;
21 while( sent != len)
22 {
23 const char* buf = static_cast<const char*>(buffer) + sent;
24 int ret = send( buf, len - sent);
25 if( ret < 0) return ret;
26 sent += static_cast<unsigned>(ret);
27 }
28 return sent;
29}
30
31void TCPSocket::listen( int backlog /* = 5 */)
32{
33 int ret = ::listen( m_socket, backlog);
34 if( ret < 0)
35 throw SocketException("listen failed, most likely another socket is already listening on the same port");
36}
37
39{
40 int ret = ::accept( m_socket, nullptr, nullptr);
41 if( ret < 0)
42 throw SocketException("TCPSocket::accept failed");
43 return Handle(ret);
44}
45
47{
48 struct pollfd poll;
49 poll.fd = m_socket;
50 poll.events = POLLIN;
51
52 int ret = TEMP_FAILURE_RETRY (::poll( &poll, 1, timeout));
53
54 if( ret == 0) return Handle();
55 if( ret < 0) throw SocketException("timedAccept failed (poll)");
56
57 ret = ::accept( m_socket, nullptr, nullptr);
58 if( ret < 0)
59 throw SocketException("TCPSocket::timedAccept failed");
60 return Handle(ret);
61}
static const int len
#define TEMP_FAILURE_RETRY(expression)
Definition TempFailure.h:8
Definition CANFrame.h:7
InternetSocket(int sockfd)
create socket from a SocketHandle returned by an accept() call
Signals a problem with the execution of a socket call.
int send(const void *buffer, size_t len)
send data through a connected socket
SocketHandle< TCPSocket > Handle
Handle for a new socket returned by accept.
Definition TCPSocket.h:14
int sendAll(const void *buffer, size_t len)
send data through a connected socket
Definition TCPSocket.cpp:18
void listen(int backlog=5)
listen for incoming connections
Definition TCPSocket.cpp:31
Handle timedAccept(int timeout) const
wait for another socket to connect
Definition TCPSocket.cpp:46
Handle accept() const
wait for another socket to connect
Definition TCPSocket.cpp:38