-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathTCPSocket.cpp
More file actions
61 lines (50 loc) · 1.36 KB
/
Copy pathTCPSocket.cpp
File metadata and controls
61 lines (50 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include "TCPSocket.h"
#include "TempFailure.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
using namespace NET;
TCPSocket::TCPSocket()
: InternetSocket( STREAM, IPPROTO_TCP)
{}
TCPSocket::TCPSocket( Handle handle)
: InternetSocket( handle.release() )
{}
int TCPSocket::sendAll( const void* buffer, size_t len)
{
size_t sent = 0;
while( sent != len)
{
const char* buf = static_cast<const char*>(buffer) + sent;
int ret = send( buf, len - sent);
if( ret < 0) return ret;
sent += static_cast<unsigned>(ret);
}
return sent;
}
void TCPSocket::listen( int backlog /* = 5 */)
{
int ret = ::listen( m_socket, backlog);
if( ret < 0)
throw SocketException("listen failed, most likely another socket is already listening on the same port");
}
TCPSocket::Handle TCPSocket::accept() const
{
int ret = ::accept( m_socket, nullptr, nullptr);
if( ret < 0)
throw SocketException("TCPSocket::accept failed");
return Handle(ret);
}
TCPSocket::Handle TCPSocket::timedAccept( int timeout) const
{
struct pollfd poll;
poll.fd = m_socket;
poll.events = POLLIN;
int ret = TEMP_FAILURE_RETRY (::poll( &poll, 1, timeout));
if( ret == 0) return Handle();
if( ret < 0) throw SocketException("timedAccept failed (poll)");
ret = ::accept( m_socket, nullptr, nullptr);
if( ret < 0)
throw SocketException("TCPSocket::timedAccept failed");
return Handle(ret);
}