libsocket 1.5
Network::TcpSocket Class Reference

This class represent a tcp connection (client and server) More...

#include <tcpsocket.hh>

Inheritance diagram for Network::TcpSocket:
Network::NetSocket Network::Socket

Public Member Functions

 TcpSocket (SOCKET_VERSION version=V4)
 
 TcpSocket (PROTO_KIND pkind, SOCKET_VERSION version=V4)
 
 TcpSocket (int socket, SOCKET_VERSION version=V4)
 
 TcpSocket (int socket, PROTO_KIND pkind, SOCKET_VERSION version=V4)
 
virtual ~TcpSocket ()
 
void connect (const std::string &hostname, int port)
 Connect as an TCP client. More...
 
std::string get_ip (TcpSocket *client) const
 return ip of client (after an accept) More...
 
TcpSocketaccept () const
 accept a new client (For server only) More...
 
void connect (int port)
 Connect as an TCP server (echo server) More...
 
void close ()
 Close the connection. More...
 
- Public Member Functions inherited from Network::NetSocket
 NetSocket (SOCKET_KIND kind, SOCKET_VERSION version=V4)
 
 NetSocket (SOCKET_KIND kind, PROTO_KIND pkind, SOCKET_VERSION version=V4)
 
virtual ~NetSocket ()
 
virtual void writeto (const std::string &str, const std::string &host, int port)
 function used to send a msg to a specific host (UDP) More...
 
std::string read ()
 function used by >> operator (read a string on current socket) More...
 
std::string read (int timeout)
 read a string with a timeout More...
 
std::string read (int &port, std::string &host)
 Get a line from socket and store client hostname and port in port and host variable. More...
 
std::string read (int &port, std::string &host, int timeout)
 Get a line from socket and store client hostname and port in port and host variable (with a timeout on listen) More...
 
std::string readn (unsigned int size)
 read a string from socket More...
 
std::string readn (int timeout, unsigned int size)
 read a string with a timeout More...
 
std::string readn (int &port, std::string &host, unsigned int size)
 Get a line from socket and store client hostname and port in port and host variable. More...
 
std::string readn (int &port, std::string &host, int timeout, unsigned int size)
 Get a line from socket and store client hostname and port in port and host variable (with a timeout on listen) More...
 
- Public Member Functions inherited from Network::Socket
 Socket (SOCKET_KIND kind, SOCKET_VERSION version=V4)
 
 Socket (SOCKET_KIND kind, PROTO_KIND pkind, SOCKET_VERSION version=V4)
 
virtual ~Socket ()
 
void write (const std::string &str)
 function used by << operator (write a string on current socket) More...
 
bool connected () const
 return true when socket is connected More...
 
int get_socket ()
 get socket (fd) warning: be very carefull with this method More...
 
void add_delim (const std::string &delim)
 set the delimitor for the text mode More...
 
void del_delim (const std::string &delim)
 delete this delimitor for the socket More...
 
void allow_empty_lines ()
 , if set, empty lines will be returned in text procols (if not, they are skipped) More...
 
void init_tls (GnuTLSKind kind, unsigned size=1024, const std::string &certfile="", const std::string &keyfile="", const std::string &trustfile="", const std::string &crlfile="")
 
void enable_tls ()
 Enable TLS on socket. More...
 
virtual std::string read ()=0
 function used by >> operator (read a string on current socket) More...
 
virtual std::string read (int timeout)=0
 read a string with a timeout More...
 
virtual std::string readn (unsigned int size)=0
 read a string from socket More...
 
virtual std::string readn (int timeout, unsigned int size)=0
 read a string with a timeout More...
 

Protected Member Functions

std::string _read_line_bin (int socket, int &port, std::string &host, unsigned int psize)
 Get a line from socket and store client hostname and port in port and host variable (when used with binary protocol) More...
 
std::string _read_line_bin (int socket, unsigned int psize)
 Get a line from socket (when used with binary protocol) More...
 
- Protected Member Functions inherited from Network::NetSocket
struct sockaddr_in _get_addr (int port) const
 internal function (construct a sockaddr) More...
 
struct sockaddr_in _get_addr (const std::string &host, int port) const
 internal function (construct a sockaddr) More...
 
int _bind (int port, const std::string &host)
 Bind a UDP server. More...
 
int _bind (int port)
 Bind a TCP server. More...
 
int _accept (int port, int server_socket) const
 Wait for a client. More...
 
std::string _get_ip (int port, int socket) const
 Get Client Ip. More...
 
void _connect (int socket, int port, const std::string &host) const
 Connect to a hostname. More...
 
std::string _read_line (int socket)
 Get a line from socket (when used with textual protocol) More...
 
std::string _read_line (int socket, int &port, std::string &host)
 Get a line from socket and store client hostname and port in port and host variable (when used with textual protocol) More...
 
virtual std::string _read_line_bin (int socket, int &port, std::string &host, unsigned int pkg_size)=0
 Get a line from socket and store client hostname and port in port and host variable (when used with binary protocol) More...
 
virtual std::string _read_line_bin (int socket, unsigned int size)=0
 Get a line from socket (when used with binary protocol) More...
 
void _write_str (int socket, const std::string &str, const std::string &host, int port) const
 Write a string to a socket to a particular host (UDP) (when used with textual protocol) More...
 
void _write_str_bin (int socket, const std::string &str, const std::string &host, int port) const
 Write a string to a socket to a particular host (UDP) (when used with binary protocol) More...
 
- Protected Member Functions inherited from Network::Socket
void _close (int socket) const
 Close a connnection. More...
 
void _listen (int socket) const
 Listen on port. More...
 
virtual std::string _read_line (int socket)=0
 Get a line from socket (when used with textual protocol) More...
 
virtual std::string _read_line_bin (int socket, unsigned int size)=0
 Get a line from socket (when used with binary protocol) More...
 
void _write_str (int socket, const std::string &str) const
 Write a string to a socket (when used with textual protocol) More...
 
void _write_str_bin (int socket, const std::string &str) const
 Write a string to a socket (when used with binary protocol) More...
 
void _set_timeout (bool enable, int socket, int timeout)
 set a timeout on a socket More...
 
std::pair< int, int > _find_delim (const std::string &str, int start) const
 
bool _update_buffer (std::pair< int, int > &delim, int &i, std::string &str)
 look delimiter and remove delimiter at begining of buffer if needed More...
 
bool _check_answer (int res, std::string &str)
 return the content of the buffer is there is More...
 

Additional Inherited Members

- Protected Attributes inherited from Network::NetSocket
int _port
 
- Protected Attributes inherited from Network::Socket
SOCKET_KIND _kind
 
SOCKET_VERSION _version
 
unsigned _state_timeout
 
int _socket
 
int _recv_flags
 
struct sockaddr_in _addr
 
PROTO_KIND _proto_kind
 
std::list< std::string > _delim
 
bool _empty_lines
 
std::string _buffer
 
bool _tls
 

Detailed Description

This class represent a tcp connection (client and server)

Author
Julien Lemoine <speedblue at happycoders dot org>

Definition at line 32 of file tcpsocket.hh.

Constructor & Destructor Documentation

◆ TcpSocket() [1/4]

Network::TcpSocket::TcpSocket ( SOCKET_VERSION  version = V4)
inline

Definition at line 35 of file tcpsocket.hh.

35 :
36 NetSocket(TCP, version)
37 {}
NetSocket(SOCKET_KIND kind, SOCKET_VERSION version=V4)
Definition: netsocket.hh:36
@ TCP
Definition: socket.hh:80

Referenced by accept().

◆ TcpSocket() [2/4]

Network::TcpSocket::TcpSocket ( PROTO_KIND  pkind,
SOCKET_VERSION  version = V4 
)
inline

Definition at line 38 of file tcpsocket.hh.

38 :
39 NetSocket(TCP, pkind, version)
40 {}

◆ TcpSocket() [3/4]

Network::TcpSocket::TcpSocket ( int  socket,
SOCKET_VERSION  version = V4 
)
inline

Definition at line 41 of file tcpsocket.hh.

41 :
42 NetSocket(TCP, version)
43 {
44 _socket = socket;
45 }

References Network::Socket::_socket.

◆ TcpSocket() [4/4]

Network::TcpSocket::TcpSocket ( int  socket,
PROTO_KIND  pkind,
SOCKET_VERSION  version = V4 
)
inline

Definition at line 46 of file tcpsocket.hh.

46 :
47 NetSocket(TCP, pkind, version)
48 {
49 _socket = socket;
50 }

References Network::Socket::_socket.

◆ ~TcpSocket()

virtual Network::TcpSocket::~TcpSocket ( )
inlinevirtual

Definition at line 52 of file tcpsocket.hh.

53 {
54 close();
55 }
void close()
Close the connection.
Definition: tcpsocket.cc:74

References close().

Member Function Documentation

◆ _read_line_bin() [1/2]

std::string Network::TcpSocket::_read_line_bin ( int  socket,
int &  port,
std::string &  host,
unsigned int  psize 
)
protectedvirtual

Get a line from socket and store client hostname and port in port and host variable (when used with binary protocol)

Exceptions
NoConnectionwhen there is no open socket
ConnectionClosedwhen there is no more connection
GetpeernameErrorwhen getpeername libc function return a negative value

Implements Network::NetSocket.

Definition at line 152 of file tcpsocket.cc.

155 {
156 char chr[MAXPKTSIZE];
157 std::string str = "";
158 int res = 1;
159 struct sockaddr_in addr;
160#ifdef IPV6_ENABLED
161 struct sockaddr_in6 addr6;
162#endif
163#ifdef LIBSOCKET_WIN
164 int size;
165#else
166 socklen_t size;
167#endif
168 bool end = false;
169 unsigned int pkg_size = 0, read = 0;
170
171#ifdef IPV6_ENABLED
172 if (V4 == _version)
173#endif
174 size = sizeof(addr);
175#ifdef IPV6_ENABLED
176 else
177 size = sizeof(addr6);
178#endif
179 if (socket < 0)
180 throw NoConnection("No Socket", HERE);
181 if (_buffer.size() >= 2 && !psize)
182 {
183 pkg_size = (unsigned char)_buffer[0] * 256 + (unsigned char)_buffer[1];
184 str = _buffer.substr(2, pkg_size);
185 if (_buffer.size() > pkg_size + 2)
186 _buffer = _buffer.substr(pkg_size + 2, _buffer.size() - pkg_size - 2);
187 else
188 _buffer = "";
189 read = str.size();
190 }
191 if (psize && _buffer.size() >= psize)
192 {
193 str = _buffer.substr(0, psize);
194 _buffer = _buffer.substr(psize, _buffer.size() - psize);
195 return str;
196 }
197 else if (!psize)
198 {
199 // _buffer.size() is 0 or 1
200#ifdef TLS
201 if (_tls)
202 res = gnutls_record_recv(_session, chr, 2 - _buffer.size());
203 else
204#endif
205 res = recv(socket, chr, 2 - _buffer.size(), 0);
206 if (res <= 1)
207 throw ConnectionClosed("Connection Closed", HERE);
208 if (_buffer.size())
209 pkg_size = (unsigned char)_buffer[0] * 256 + (unsigned char)chr[0];
210 else
211 pkg_size = (unsigned char)chr[0] * 256 + (unsigned char)chr[1];
212 _buffer = "";
213 }
214 else
215 {
216 // _buffer contains less characters than size, so copy
217 // _bufer in str and clear _buffer.
218 str = _buffer;
219 _buffer = "";
220 pkg_size = psize;
221 read = str.size();
222 }
223 while (!end)
224 {
225#ifdef TLS
226 if (_tls)
227 res = gnutls_record_recv(_session, chr, size - read);
228 else
229#endif
230 res = recv(socket, chr, size - read, 0);
231#ifdef IPV6_ENABLED
232 if (V4 == _version)
233#endif
234 if (getpeername(socket, (struct sockaddr *) &addr, &size) < 0)
235 throw GetpeernameError("getpeername error", HERE);
236#ifdef IPV6_ENABLED
237 else
238 if (getpeername(socket, (struct sockaddr *) &addr6, &size) < 0)
239 throw GetpeernameError("getpeername error", HERE);
240#endif
241 if (res <= 0)
242 throw ConnectionClosed("Connection Closed", HERE);
243 str += std::string(chr, res).substr(0, res);
244 read += res;
245 if (read >= pkg_size)
246 end = true;
247 }
248#ifdef IPV6_ENABLED
249 if (V4 == _version)
250 {
251#endif
252 host = std::string(inet_ntoa(addr.sin_addr));
253 port = ntohs(addr.sin_port);
254#ifdef IPV6_ENABLED
255 }
256 else
257 {
258 char buf[INET6_ADDRSTRLEN];
259 if (inet_ntop(AF_INET6, &addr6.sin6_addr, buf, INET6_ADDRSTRLEN) == 0)
260 throw InetntopError("Not a valid address", HERE);
261 host = std::string(buf);
262 port = ntohs(addr6.sin6_port);
263 }
264#endif
265 return str;
266 }
std::string read()
function used by >> operator (read a string on current socket)
Definition: netsocket.cc:533
std::string _buffer
Definition: socket.hh:202
SOCKET_VERSION _version
Definition: socket.hh:191
@ V4
Definition: socket.hh:87
#define HERE

References Network::Socket::_buffer, Network::Socket::_tls, Network::Socket::_version, HERE, Network::NetSocket::read(), and Network::V4.

◆ _read_line_bin() [2/2]

std::string Network::TcpSocket::_read_line_bin ( int  socket,
unsigned int  psize 
)
protectedvirtual

Get a line from socket (when used with binary protocol)

Exceptions
NoConnectionwhen there is no open socket
ConnectionClosedwhen there is no more connection

Implements Network::NetSocket.

Definition at line 81 of file tcpsocket.cc.

82 {
83 char chr[MAXPKTSIZE];
84 std::string str = "";
85 int res = 1;
86 unsigned int size = 0, read = 0;
87 bool end = false;
88
89 if (socket < 0)
90 throw NoConnection("No Socket", HERE);
91 if (_buffer.size() >= 2 && !psize)
92 {
93 size = (unsigned char)_buffer[0] * 256 + (unsigned char)_buffer[1];
94 str = _buffer.substr(2, size);
95 if (_buffer.size() > size + 2)
96 _buffer = _buffer.substr(size + 2, _buffer.size() - size - 2);
97 else
98 _buffer = "";
99 read = str.size();
100 }
101 if (psize && _buffer.size() >= psize)
102 {
103 str = _buffer.substr(0, psize);
104 _buffer = _buffer.substr(psize, _buffer.size() - psize);
105 return str;
106 }
107 else if (!psize)
108 {
109 // _buffer.size() is 0 or 1
110#ifdef TLS
111 if (_tls)
112 res = gnutls_record_recv(_session, chr, 2 - _buffer.size());
113 else
114#endif
115 res = recv(socket, chr, 2 - _buffer.size(), 0);
116 if (res <= 1)
117 throw ConnectionClosed("Connection Closed", HERE);
118 if (_buffer.size())
119 size = (unsigned char)_buffer[0] * 256 + (unsigned char)chr[0];
120 else
121 size = (unsigned char)chr[0] * 256 + (unsigned char)chr[1];
122 _buffer = "";
123 }
124 else
125 {
126 // _buffer contains less characters than size, so copy
127 // _bufer in str and clear _buffer.
128 str = _buffer;
129 _buffer = "";
130 size = psize;
131 read = str.size();
132 }
133 while (!end)
134 {
135 memset(chr, 0, MAXPKTSIZE);
136#ifdef TLS
137 if (_tls)
138 res = gnutls_record_recv(_session, chr, size - read);
139 else
140#endif
141 res = recv(socket, chr, size - read, 0);
142 if (res <= 0)
143 throw ConnectionClosed("Connection Closed", HERE);
144 str += std::string(chr, res).substr(0, res);
145 read += res;
146 if (read >= size)
147 end = true;
148 }
149 return str;
150 }

References Network::Socket::_buffer, Network::Socket::_tls, HERE, and Network::NetSocket::read().

◆ accept()

TcpSocket * Network::TcpSocket::accept ( ) const

accept a new client (For server only)

Definition at line 42 of file tcpsocket.cc.

43 {
44 TcpSocket* res;
45
46#ifdef IPV6_ENABLED
47 if (V4 == _version)
48#endif
49 res = new TcpSocket(_accept(_port, _socket));
50#ifdef IPV6_ENABLED
51 else
52 res = new TcpSocket(_accept(_port, _socket), V6);
53#endif
54 res->_port = _port;
55 res->_proto_kind = _proto_kind;
56#ifdef TLS
57 if (_tls)
58 {
59 res->_tls = true;
60 res->_tls_main = false;
61 res->_session = _session;
62 res->_x509_cred = _x509_cred;
63 res->enable_tls();
64 }
65#endif
66 return res;
67 }
int _accept(int port, int server_socket) const
Wait for a client.
Definition: netsocket.cc:211
PROTO_KIND _proto_kind
Definition: socket.hh:199
TcpSocket(SOCKET_VERSION version=V4)
Definition: tcpsocket.hh:35
@ V6
Definition: socket.hh:88

References Network::NetSocket::_accept(), Network::NetSocket::_port, Network::Socket::_proto_kind, Network::Socket::_socket, Network::Socket::_tls, Network::Socket::_version, Network::Socket::enable_tls(), TcpSocket(), Network::V4, and Network::V6.

◆ close()

void Network::TcpSocket::close ( )

Close the connection.

Definition at line 74 of file tcpsocket.cc.

75 {
76 if (_socket > 0)
78 _socket = 0;
79 }
void _close(int socket) const
Close a connnection.
Definition: socket.cc:167

References Network::Socket::_close(), and Network::Socket::_socket.

Referenced by ~TcpSocket().

◆ connect() [1/2]

void Network::TcpSocket::connect ( const std::string &  hostname,
int  port 
)

Connect as an TCP client.

Here is an example of tcp client using libsocket :

#include <stdlib.h>
#include <iostream>
#include <string>
#include "socket/tcpsocket.hh"

int main(int argc, char **argv)
{
  Network::TcpSocket            client;
  std::string                   str;

  if (argc < 3)
    {
      std::cout << "Use: " << argv[0] << " port hostname" << std::endl;
      exit(0);
    }
  try
    {
      client.connect(std::string(argv[2]), strtol(argv[1], NULL, 10));
      client >> str;
      std::cout << str << std::endl;

      while (str != "quit")
        {
          std::cin >> str;
          client << str;
          client >> str;
        }
      client.close();
      exit (0);
    }
  catch (Network::Exception e) // catch all libsocket errors
    {
      std::cerr << e;
      exit(1);
    }

}

Definition at line 28 of file tcpsocket.cc.

29 {
30 _port = port;
31 _socket = _bind(port, hostname);
32 _connect(_socket, port, hostname);
33 }
int _bind(int port, const std::string &host)
Bind a UDP server.
Definition: netsocket.cc:86
void _connect(int socket, int port, const std::string &host) const
Connect to a hostname.
Definition: netsocket.cc:186

References Network::NetSocket::_bind(), Network::NetSocket::_connect(), Network::NetSocket::_port, and Network::Socket::_socket.

◆ connect() [2/2]

void Network::TcpSocket::connect ( int  port)

Connect as an TCP server (echo server)

Here is an example of tcp server using libsocket :

#include <stdlib.h>
#include <iostream>
#include <string>
#include "socket/tcpsocket.hh"

int main(int argc, char **argv)
{
  Network::TcpSocket            server;
  Network::TcpSocket            *client;
  std::string                   str;

  if (argc < 2)
    {
      std::cout << "Use: " << argv[0] << " port" << std::endl;
      exit(0);
    }
  try
    {
      std::cout << "--- echo server ---" << std::endl;
      server.connect(strtol(argv[1], NULL, 10));
      client = server.accept();
      (*client) << "Welcome on test server";
      while (str != "quit")
               {

                 //(*client) >> str;
                 // read with a timeout of 30 second and get port and host
                 str = client->read(port, host, 30);
                 std::cout << "[" << str << "] from [" << host << ":"
                           << port << "]" << std::endl;
                 (*client) << str;
               }
      server.close();
      exit (0);
    }
  catch (Network::Exception e) // catch all libsocket errors
    {
      std::cerr << e;
      exit(1);
    }
}

Definition at line 35 of file tcpsocket.cc.

36 {
37 _port = port;
38 _socket = _bind(port);
40 }
void _listen(int socket) const
Listen on port.
Definition: socket.cc:192

References Network::NetSocket::_bind(), Network::Socket::_listen(), Network::NetSocket::_port, and Network::Socket::_socket.

◆ get_ip()

std::string Network::TcpSocket::get_ip ( TcpSocket client) const

return ip of client (after an accept)

Definition at line 69 of file tcpsocket.cc.

70 {
71 return _get_ip(_port, client->_socket);
72 }
std::string _get_ip(int port, int socket) const
Get Client Ip.
Definition: netsocket.cc:243

References Network::NetSocket::_get_ip(), Network::NetSocket::_port, and Network::Socket::_socket.


The documentation for this class was generated from the following files: