Skip to content

sockets::Connection

Isaac Avram edited this page Dec 7, 2018 · 5 revisions

The Connection class represents an established network connection. Instances of the class may be moved, but are not copyable. This class takes one template argument, which is normally TCPSocket. As such, TCPConnection is equivalent to Connection<TCPSocket>.

A custom Socket type may be passed as a template argument to Connection. This type must be move-constructable, move-assignable, implement the following methods:

Method Prototype Description Return
recv(ByteBuffer& buffer, size_t limit, size_t offset, int flags) Reads bytes into the given ByteBuffer beginning at the offset, up to the provided limit. The method is expected to resize the buffer to fit the data. If no data is available, the method blocks until ready. The number of bytes read.
send(const ByteBuffer& buffer, size_t offset, int flags) Writes all the bytes beginning at the offset to the socket. The number of bytes sent.
invalid() Returns true if the Socket is invalid, false otherwise bool

Normally this class is not instantiated directly, but created using the connect_to() method.

Connection::read(size_t n)

Reads up to n bytes from the network. Returns a reference to a ByteBuffer containing the data read. If no data is available, this method blocks until ready.

Throws

ClosedError if the connection is marked as closed.

InvalidSocketError if the socket is invalid.

SocketReadError may be thrown by the internal socket class from a read() call.

Connection::read_exactly(size_t n)

Reads exactly n bytes. Returns a reference to a ByteBuffer containing the data read. This method blocks until exactly n bytes are read, or an exception is thrown.

Throws

ClosedError if the connection is marked as closed.

InvalidSocketError if the socket is invalid.

SocketReadError may be thrown by the internal socket class from a read() call.

template<size_t delim_size> Connection::read_until(const ByteString<delim_size>& delim)

Reads data until delim is encountered. Returns a reference to a ByteBuffer containing all data read up to the delimiter. Any bytes read after the delimiter are discarded. This method blocks until the delimiter is encountered.

Throws

ClosedError if the connection is marked as closed.

InvalidSocketError if the socket is invalid.

SocketReadError may be thrown by the internal socket class from a read() call.

template Connection::write(Iter begin, Iter end)

Writes all bytes from the iterator. Returns the number of bytes written.

template<size_t data_size> Connection::write(const ByteString<data_size> &data)

Writes all bytes in the ByteString. Returns the number of bytes written.

Connection::get_socket()

Returns a reference to the underlying Socket.

Connection::get_name()

Returns a std::string containing the ip address of the connected peer.

Connection::closed()

Returns true if the connection has been closed. False otherwise.