SourcePro® API Reference Guide

Product Documentation:
   SourcePro
Documentation Home
List of all members | Public Member Functions | Protected Member Functions | Static Protected Member Functions | Protected Attributes | Related Functions
RWSocket Class Reference

Wrapper for the C concept of a socket. More...

#include <rw/network/RWSocket.h>

Inheritance diagram for RWSocket:
RWMulticastSocket

Public Member Functions

 RWSocket ()
 
 RWSocket (const RWSocket &s)
 
 RWSocket (const RWSockType &socketType)
 
 RWSocket (SOCKET existingSocket)
 
RWSocket accept (RWSockAddr *addr=0) const
 
void bind (const RWSockAddrBase &address)
 
void close ()
 
void closesocket ()
 
void connect (const RWSockAddrBase &address)
 
RWSockAddr getpeername () const
 
SOCKET getSocket () const
 
RWSockAddr getsockname () const
 
void getsockopt (int level, int option, void *optval, RWSockLenType *optlen) const
 
int getsockopt (int option) const
 
RWSockType getsocktype () const
 
RWCString id (unsigned level=0) const
 
void ioctl (long cmd, void *arg) const
 
void ioctl (long cmd, int arg) const
 
int ioctl (long cmd) const
 
void ioctlsocket (long cmd, void *arg) const
 
void ioctlsocket (long cmd, int arg) const
 
int ioctlsocket (long cmd) const
 
bool isValid () const
 
void listen (const RWSockAddrBase &addr, int backlog=5)
 
void listen (int backlog=5) const
 
RWSocketoperator= (const RWSocket &s)
 
RWNetBuf recv (int flags=0) const
 
int recv (char *buf, int len, int flags=0, RWNetBuf::State *s=0) const
 
RWNetBuf recvAtLeast (int n) const
 
int recvAtLeast (char *buf, int len, int n, RWNetBuf::State *s=0) const
 
RWNetBuf recvfrom (RWSockAddr *addr=0, int flags=0) const
 
int recvfrom (char *buf, int len, RWSockAddr *addr=0, int flags=0, RWNetBuf::State *state=0) const
 
int recvmsg (msghdr *msg, int flags=0, RWNetBuf::State *s=0) const
 
int send (const RWCString &buf, int flags=0) const
 
int send (const char *buf, int len, int flags=0) const
 
void sendAtLeast (const RWCString &buf) const
 
int sendAtLeast (const RWCString &buf, int n) const
 
void sendAtLeast (const char *buf, int len) const
 
int sendAtLeast (const char *buf, int len, int n) const
 
int sendmsg (msghdr *msg, int flags=0) const
 
int sendto (const RWCString &buf, const RWSockAddrBase &to, int flags=0) const
 
int sendto (const char *buf, int len, const RWSockAddrBase &to, int flags=0) const
 
void setsockopt (int level, int option, void *optval, int optlen) const
 
void setsockopt (int option, int optval) const
 
void shutdown (int how=2) const
 
void shutdownread () const
 
void shutdownwrite () const
 
void socket (const RWSockType &type)
 

Protected Member Functions

void clearError () const
 
int lastError () const
 
void raise (const char *funcName, int err) const
 
void raise (const char *funcName) const
 
void raiseUnlessWouldBlock (const char *funcName, int err) const
 
void raiseUnlessWouldBlock (const char *funcName) const
 

Static Protected Member Functions

static void doRaise (int err, const char *funcName)
 

Protected Attributes

SOCKET socket_
 

Related Functions

(Note that these are not member functions.)

bool operator!= (const RWSocket &lhs, const RWSocket &rhs)
 
std::ostream & operator<< (std::ostream &, const RWSocket &sock)
 
bool operator== (const RWSocket &lhs, const RWSocket &rhs)
 
void rwSetBlocking (RWSocket &s)
 
void rwSetNonBlocking (RWSocket &s)
 
#define SET_BLOCKING(rwsocket)
 
#define SET_NON_BLOCKING(rwsocket)
 
typedef int SOCKET
 

Detailed Description

RWSocket is a wrapper for the C concept of a socket. Its member functions correspond exactly to the C functions in the Berkeley sockets API. Typically, RWSocket member functions have the same names as the corresponding C API functions, but the arguments and return values may be different to reflect the C++ environment. For example, many member functions have default arguments to handle the most common cases. Some member functions take alternate parameter types that simplify the interface (for example, using the RWSockAddrBase class instead of the sockaddr structure). Sometimes, multiple overloads of a member function exist to provide alternate APIs for different occasions.

Almost all Berkeley sockets calls that use a single socket are encapsulated in this class. Omitted calls include:

In addition to the functions that match the sockets API, some convenience functions are included. They are id(), isValid(), getSocket(), recvAtLeast(), and sendAtLeast().

The socket is not shut down by a destructor. It must be explicitly shut down by calling close(), closesocket(), or shutdown(). Use the RWPortal layer for objects that close the portal automatically using a destructor.

RWSocket has no state. All state (such as whether the socket blocks) is kept in the communications channel.

The Networking package provides a C++ wrapper for the native socket API. As a result, return values from socket API calls are returned to the caller unaltered.

Note
This can result in different return values and, in some cases, different behavior between calls to the same member functions on different platforms (BSD or Winsock, for instance).

For example, a connect call on a non-blocking socket returns with EINPROGRESS from BSD, but returns with WSAVEWOULDBLOCK from Winsock. You should consult your implementation-specific user's guide to identify expected behavior.

Constructor & Destructor Documentation

RWSocket::RWSocket ( )

The default constructor sets the socket to an invalid state. You must initialize it with a call to socket(), connect(), bind(), or listen() before it can be used.

RWSocket::RWSocket ( const RWSocket s)

Creates an RWSocket that encapsulates the same C socket as s.

RWSocket::RWSocket ( const RWSockType socketType)

Creates an unconnected socket of the specified type. The resulting socket must be bound to an address using bind(), connect(), or listen() before it can be used.

RWSocket::RWSocket ( SOCKET  existingSocket)

Creates an RWSocket that encapsulates the C socket.

Member Function Documentation

RWSocket RWSocket::accept ( RWSockAddr addr = 0) const

Accepts a connection that is waiting at this socket. A queue for incoming connections must first be created using listen(). If addr is non-null, the peer's address is returned in addr. You can also get this information by calling getpeername() on the returned RWSocket.

If the socket is set to block (the default), then accept() blocks until a connection request arrives. If the socket is set to be non-blocking, accept() returns right away. If no connections are available, the returned socket is invalid (use isValid() to check) and *addr is unchanged.

void RWSocket::bind ( const RWSockAddrBase address)

Assigns an address to an as-yet unnamed socket. This function is used primarily by servers that need to specify the port on which they wait for connections.

Note
When the bind() member function is invoked on an uninitialized socket, the function initializes the socket and sets the SO_REUSEADDR option on the socket. If you do not want this option to be set, call the socket() member function to initialize the socket before you invoke bind(). See section "Socket Security" under Chapter 8, "The Windows Socket Adapter" in the Essential Networking Module User's Guide for more information.
void RWSocket::clearError ( ) const
protected

Sets the error code to no error. To make your application portable, use this function instead of the underlying OS specific function calls.

void RWSocket::close ( )

Terminates the connection and removes the socket. The socket is set to an invalid state. Unless this socket is being shared with another process, the resources used to maintain the socket are deallocated and any unread data is discarded.

void RWSocket::closesocket ( )

Alias for close().

void RWSocket::connect ( const RWSockAddrBase address)

Connects to a remote socket. If it is a stream socket, connect() performs the initial handshaking with the remote side. If it is a datagram socket, connect() sets up the target for communication, but data is not sent. If the socket has not been initialized with socket(), then connect() initializes it.

static void RWSocket::doRaise ( int  err,
const char *  funcName 
)
staticprotected
Deprecated:
As of SourcePro 4, use raise(const char*, int) instead.

Throws an RWSocketError exception based on the value of the parameter err.

RWSockAddr RWSocket::getpeername ( ) const

Returns the address of the peer connected to this socket.

SOCKET RWSocket::getSocket ( ) const
inline

Returns the C API socket descriptor encapsulated in RWSocket.

RWSockAddr RWSocket::getsockname ( ) const

Returns the address of this socket.

void RWSocket::getsockopt ( int  level,
int  option,
void *  optval,
RWSockLenType optlen 
) const

Determines a socket option setting.

int RWSocket::getsockopt ( int  option) const

Determines a socket option setting. Assumes the SOL_SOCKET level and an integer option, which is the usual case.

RWSockType RWSocket::getsocktype ( ) const

Returns the type information for this socket.

RWCString RWSocket::id ( unsigned  level = 0) const

Returns a string describing self. The verbosity of the output is controlled by level, where level=0 is the most basic output, and level=9 is the most verbose. If not specified, a default value of 0 is used and is guaranteed not to block.

Grammar Definitions

ocal_addr ::= <the result of getsockname().id(level> peer_addr ::= <the result of getpeername().id(level> 
Socket State Output Grammar
isValid() == false "invalid"
bind() call failed "no address"
connected local_addr "-->" peer_addr
bound local_addr
void RWSocket::ioctl ( long  cmd,
void *  arg 
) const

Gets or retrieves socket operating parameters.

void RWSocket::ioctl ( long  cmd,
int  arg 
) const

Gets or retrieves socket operating parameters. This overload is useful for commands that expect an integer argument and return nothing (such as FIONBIO).

This function is commonly used to set blocking or non-blocking mode on a socket. To set a socket to non-blocking, use ioctl(FIONBIO,1). To set it to blocking, use ioctl(FIONBIO,0).

Note
You can also use the global functions rwSetBlocking() and rwSetNonBlocking() to set the blocking mode on an RWSocket.
int RWSocket::ioctl ( long  cmd) const

Gets or retrieves socket operating parameters. This overload is useful for commands that return ints (like FIONREAD or SIOCATMARK).

void RWSocket::ioctlsocket ( long  cmd,
void *  arg 
) const
void RWSocket::ioctlsocket ( long  cmd,
int  arg 
) const
int RWSocket::ioctlsocket ( long  cmd) const

Alias for ioctl(long) const

bool RWSocket::isValid ( ) const

Verifies that the socket is ready for use.

int RWSocket::lastError ( ) const
protected

Returns the last error on this socket. To make your application portable, use this function instead of the underlying OS specific function calls.

void RWSocket::listen ( const RWSockAddrBase addr,
int  backlog = 5 
)

Prepares a socket to accept incoming connections. The backlog parameter specifies the number of incoming connection requests that the protocol software enqueues while a connection is being processed.

Note
When the listen() member function is invoked on an uninitialized socket, the function initializes the socket and sets the SO_REUSEADDR option on the socket. If you do not want this option to be set, call the socket() member function to initialize the socket before you invoke listen(). See section "Socket Security" under Chapter 8, "The Windows Socket Adapter" in the Essential Networking Module User's Guide for more information.
void RWSocket::listen ( int  backlog = 5) const

Prepares a bound socket to accept incoming connections. The backlog parameter specifies the number of incoming connection requests that the protocol software enqueues while a connection is being processed.

RWSocket& RWSocket::operator= ( const RWSocket s)

Assigns the underlying C socket from s to self. Both s and self will share the same underlying C socket.

void RWSocket::raise ( const char *  funcName,
int  err 
) const
protected

Throws an RWSocketError exception based on the error code passed in the parameter.

void RWSocket::raise ( const char *  funcName) const
protected
Deprecated:
As of SourcePro 4, use raise(const char*, int) in conjunction with lastError().
void RWSocket::raiseUnlessWouldBlock ( const char *  funcName,
int  err 
) const
protected

Throws an RWSocketError exception based on the error code passed in the parameter.

void RWSocket::raiseUnlessWouldBlock ( const char *  funcName) const
protected
Deprecated:
As of SourcePro 4, use raiseUnlessWouldBlock(const char*, int) in conjunction with lastError().
RWNetBuf RWSocket::recv ( int  flags = 0) const

Receives data from the socket. recv() is used to read data from a connected socket. The flags parameter is formed by ORing one or more of MSG_OOB (out of band data), or MSG_PEEK (peek at data on the socket but do not consume it). The variant that uses an explicit buffer returns the number of bytes actually received. This may be zero in the case of a non-blocking socket without data waiting. If an error occurs, an RWSocketError exception is thrown.

int RWSocket::recv ( char *  buf,
int  len,
int  flags = 0,
RWNetBuf::State s = 0 
) const

Receives data from the socket. recv() is used to read data from a connected socket. The flags parameter is formed by ORing one or more of MSG_OOB (out of band data), or MSG_PEEK (peek at data on the socket but do not consume it). The variant that uses an explicit buffer returns the number of bytes actually received. This may be zero in the case of a non-blocking socket without data waiting. If an error occurs, an RWSocketError exception is thrown.

RWNetBuf RWSocket::recvAtLeast ( int  n) const

This is guaranteed to either receive n characters or throw an exception. The call is only valid for stream sockets. The implementation loops over recv() until all data has been received. An RWNetCantRecvError exception is thrown if one of the calls to recv() returns no data. If you call recvAtLeast() on a non-blocking socket, it will probably throw an exception.

int RWSocket::recvAtLeast ( char *  buf,
int  len,
int  n,
RWNetBuf::State s = 0 
) const

This is guaranteed to either receive n characters or throw an exception. The call is only valid for stream sockets. The implementation loops over recv() until all data has been received. An RWNetCantRecvError exception is thrown if one of the calls to recv() returns no data. If you call recvAtLeast() on a non-blocking socket, it will probably throw an exception.

RWNetBuf RWSocket::recvfrom ( RWSockAddr addr = 0,
int  flags = 0 
) const

Receives data from the socket, and can be used on any socket. The flags parameter is formed by ORing one or more of MSG_OOB (out of band data) or MSG_PEEK (peek at data on the socket but do not consume it). addr, if it is specified and if the socket is a datagram socket, becomes the address of the originator of the message.

int RWSocket::recvfrom ( char *  buf,
int  len,
RWSockAddr addr = 0,
int  flags = 0,
RWNetBuf::State state = 0 
) const

Receives data from the socket, and can be used on any socket. The flags parameter is formed by ORing one or more of MSG_OOB (out of band data) or MSG_PEEK (peek at data on the socket but do not consume it). addr, if it is specified and if the socket is a datagram socket, becomes the address of the originator of the message. This overload returns the number of bytes actually received. This may be zero in the case of a non-blocking socket without data waiting.

int RWSocket::recvmsg ( msghdr *  msg,
int  flags = 0,
RWNetBuf::State s = 0 
) const

Alias for recvfrom(char*,int,RWSockAddr*,int,RWNetBuf::State*)const.

Condition:
This method is available only on systems that provide struct msghdr.
int RWSocket::send ( const RWCString buf,
int  flags = 0 
) const

Sends data from a connected socket. These functions return the number of bytes sent. If an error occurs, an RWSocketError exception is thrown.

Note
When calling send(), the application must check the number of bytes sent, and resend if necessary. The sendAtLeast() method guarantees the transmission of the number of bytes specified (or the entire buffer if no size is specified).
Sending data on a closed socket may result in the generation of a SIGPIPE signal from the underlying socket library. Avoid this by checking that the socket's sock_attr_canwrite attribute is true before each call to send(). Refer to RWSocketAttribute for details on checking socket attributes. Alternatively, you can use a signal handler to explicitly handle or ignore SIGPIPE.
int RWSocket::send ( const char *  buf,
int  len,
int  flags = 0 
) const

Sends data from a connected socket. These functions return the number of bytes sent. If an error occurs, an RWSocketError exception is thrown.

Note
When calling send(), the application must check the number of bytes sent, and resend if necessary. The sendAtLeast() method guarantees the transmission of the number of bytes specified (or the entire buffer if no size is specified).
Sending data on a closed socket may result in the generation of a SIGPIPE signal from the underlying socket library. Avoid this by checking that the socket's sock_attr_canwrite attribute is true before each call to send(). Refer to RWSocketAttribute for details on checking socket attributes. Alternatively, you can use a signal handler to explicitly handle or ignore SIGPIPE.
void RWSocket::sendAtLeast ( const RWCString buf) const

Guaranteed to send at least n characters or the entire buffer if n is not specified. This call is valid only for stream sockets. The implementation loops over send() to send the data. If any of the calls to send cannot send any data, an RWNetCantSendError exception is thrown. If you call sendAtLeast() on a non-blocking socket, it will probably throw an exception if n is greater than the amount of unused space in the system's buffer for the socket.

int RWSocket::sendAtLeast ( const RWCString buf,
int  n 
) const

Guaranteed to send at least n characters or the entire buffer if n is not specified. This call is valid only for stream sockets. The implementation loops over send() to send the data. If any of the calls to send cannot send any data, an RWNetCantSendError exception is thrown. If you call sendAtLeast() on a non-blocking socket, it will probably throw an exception if n is greater than the amount of unused space in the system's buffer for the socket.

void RWSocket::sendAtLeast ( const char *  buf,
int  len 
) const

Guaranteed to send at least n characters or the entire buffer if n is not specified. This call is valid only for stream sockets. The implementation loops over send() to send the data. If any of the calls to send cannot send any data, an RWNetCantSendError exception is thrown. If you call sendAtLeast() on a non-blocking socket, it will probably throw an exception if n is greater than the amount of unused space in the system's buffer for the socket.

int RWSocket::sendAtLeast ( const char *  buf,
int  len,
int  n 
) const

Guaranteed to send at least n characters or the entire buffer if n is not specified. This call is valid only for stream sockets. The implementation loops over send() to send the data. If any of the calls to send cannot send any data, an RWNetCantSendError exception is thrown. If you call sendAtLeast() on a non-blocking socket, it will probably throw an exception if n is greater than the amount of unused space in the system's buffer for the socket.

int RWSocket::sendmsg ( msghdr *  msg,
int  flags = 0 
) const

Alias for sendto(const char*, int, const RWSockAddrBase&, int) const.

Condition:
This method is available only on systems that provide struct msghdr.
int RWSocket::sendto ( const RWCString buf,
const RWSockAddrBase to,
int  flags = 0 
) const

Send data from a socket, and can be used on any socket. The to parameter is ignored for a connected socket. These functions return the number of bytes sent. This is zero if the socket is non-blocking and the internal buffer for the socket is full.

int RWSocket::sendto ( const char *  buf,
int  len,
const RWSockAddrBase to,
int  flags = 0 
) const

Send data from a socket, and can be used on any socket. The to parameter is ignored for a connected socket. These functions return the number of bytes sent. This is zero if the socket is non-blocking and the internal buffer for the socket is full.

void RWSocket::setsockopt ( int  level,
int  option,
void *  optval,
int  optlen 
) const

Sets a socket option setting. The second function assumes the SOL_SOCKET level and an integer option, which is the usual case.

void RWSocket::setsockopt ( int  option,
int  optval 
) const

Sets a socket option setting. The second function assumes the SOL_SOCKET level and an integer option, which is the usual case.

void RWSocket::shutdown ( int  how = 2) const

Shuts down either the reading side (how=0), the writing side (how=1), or both sides (how=2) of a full duplex connection. Use close() or closesocket() to deallocate the socket resources.

void RWSocket::shutdownread ( ) const
inline

Shuts down one side of the connection.

void RWSocket::shutdownwrite ( ) const
inline

Shuts down one side of the connection.

void RWSocket::socket ( const RWSockType type)

Creates an unconnected socket of the specified type. The resulting socket must be bound to an address using bind(), connect(), or listen() before it can be used.

Friends And Related Function Documentation

bool operator!= ( const RWSocket lhs,
const RWSocket rhs 
)
related

Returns false if the two sockets refer to the same underlying communications channel.

std::ostream & operator<< ( std::ostream &  ,
const RWSocket sock 
)
related

Outputs a representation of x on strm. The representation is generated using the member function x.id() with level=0.

Note
This class does not have an extraction (>>) operator.
bool operator== ( const RWSocket lhs,
const RWSocket rhs 
)
related

Returns true if the two sockets refer to the same underlying communications channel.

void rwSetBlocking ( RWSocket s)
related

Sets an RWSocket into blocking mode.

void rwSetNonBlocking ( RWSocket s)
related

Sets an RWSocket into non-blocking mode.

#define SET_BLOCKING (   rwsocket)
related
Deprecated:
As of SourcePro 1, use rwSetBlocking() instead.
#define SET_NON_BLOCKING (   rwsocket)
related
Deprecated:
As of SourcePro 1, use rwSetNonBlocking() instead.
typedef int SOCKET
related

SOCKET is the type used by the underlying implementation as a reference to the communication channel.

Member Data Documentation

SOCKET RWSocket::socket_
protected

Contains the socket itself. No other state is stored in this class. All state information related to the socket is kept in the socket.

Copyright © 2021 Rogue Wave Software, Inc., a Perforce company. All Rights Reserved.