simple-socket library 1.1.5

TCPSocket.cpp

Go to the documentation of this file.
00001 #include "TCPSocket.h"
00002 #include "TempFailure.h"
00003 
00004 #include <sys/socket.h>
00005 #include <netinet/in.h>
00006 #include <poll.h>
00007 
00008 using namespace NET;
00009 
00010 TCPSocket::TCPSocket()
00011 : InternetSocket( STREAM, IPPROTO_TCP)
00012 {}
00013 
00014 TCPSocket::TCPSocket( Handle handle)
00015 : InternetSocket( handle.release() )
00016 {}
00017 
00018 int TCPSocket::sendAll( const void* buffer, size_t len)
00019 {
00020     size_t sent = 0;
00021     while( sent != len)
00022     {
00023         const char* buf = static_cast<const char*>(buffer) + sent;
00024         int ret = send( buf, len - sent);
00025         if( ret < 0) return ret;
00026         sent += static_cast<unsigned>(ret);
00027     }
00028     return sent;
00029 }
00030 
00031 void TCPSocket::listen( int backlog /* = 5 */)
00032 {
00033     int ret = ::listen( m_socket, backlog);
00034     if( ret < 0)
00035         throw SocketException("listen failed, most likely another socket is already listening on the same port");
00036 }
00037 
00038 TCPSocket::Handle TCPSocket::accept() const
00039 {
00040     int ret = ::accept( m_socket, 0, 0);
00041     if( ret < 0)
00042         throw SocketException("TCPSocket::accept failed");
00043     return Handle(ret);
00044 }
00045 
00046 TCPSocket::Handle TCPSocket::timedAccept( int timeout) const
00047 {
00048     struct pollfd poll;
00049     poll.fd = m_socket;
00050     poll.events = POLLIN;
00051 
00052     int ret = TEMP_FAILURE_RETRY (::poll( &poll, 1, timeout));
00053 
00054     if( ret == 0) return Handle();
00055     if( ret < 0) throw SocketException("Poll failed (receive)");
00056 
00057     ret = ::accept( m_socket, 0, 0);
00058     if( ret < 0)
00059         throw SocketException("TCPSocket::timedAccept failed");
00060     return Handle(ret);
00061 }