Module: Essential Networking Module Package: Networking
Does not inherit
#include <rw/network/RWSocket.h>
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 overloadings of a member function exist to provide alternate APIs for different occasions.
Almost all of the Berkeley sockets calls that use a single socket are encapsulated in this class. Omitted calls include:
The database calls of form getXbyY (for example, gethostbyname), and IP address conversion routines (for example, inet_ntoa()). These are encapsulated by the RWInetHost and RWInetPort classes.
The host-network conversion calls, such as htons(). These calls are not needed -- the C++ API does the conversions automatically.
select(). This is encapsulated by the RWSocketAttribute class.
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.
SOCKET
SOCKET is the type used by the underlying implementation as a reference to the communication channel.
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(const RWSocket&);
Creates another portal into the same communications channel.
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(SOCKET existingSocket);
Creates an RWSocket that encapsulates the C socket.
bool operator==(const RWSocket& s) const;
Returns true if the two sockets refer to the same underlying communications channel.
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 valid() to check) and *addr is unchanged.
void 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().
void close(); void closesocket();
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.
close() and closesocket() are synonyms. Usually, Unix developers use close() and Winsock developers use closesocket().
void 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.
RWSockAddr getpeername() const;
Returns the address of the peer connected to this socket.
SOCKET getSocket() const;
Returns the C API socket descriptor encapsulated in RWSocket.
RWSockAddr getsockname() const;
Returns the address of this socket.
void getsockopt(int level, int option, void *optval,
RWSockLenType *optlen) const; int getsockopt(int option) const;
Determines a socket option setting. The second function assumes the SOL_SOCKET level and an integer option, which is the usual case.
RWSockType getsocktype() const;
Returns the type information for this socket.
RWCString 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, and level=9 is the most verbose.
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;
Gets or sets socket operating parameters. The versions that return an integer are useful with commands that return ints (like FIONREAD or SIOCATMARK). The versions that take an integer argument are useful with commands that expect an integer argument and return nothing (like FIONBIO). The ioctlsocket() functions are aliases for ioctl().
The ioctl() functions are 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). You can also use the global functions rwSetBlocking() and rwSetNonBlocking() to set the blocking mode on an RWSocket.
bool isValid() const;
Verifies that the socket is ready for use.
void listen(int backlog=5) const; void 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. If the address is not provided, it must first be set using bind().
RWNetBuf recv(int flags=0) const; int 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 recvAtLeast(int n) const; int 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 of the data has been sent. 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 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;
Receives data from the socket. recvfrom() and recvmsg() 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. 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.
int send(const RWCString& buf, int flags=0) const; int 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).
NOTE -- 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 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;
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 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; int sendmsg(msghdr *msg, int flags=0) const;
sendto() and sendmsg() send data 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 setsockopt(int level, int option, void *optval, int optlen) const; void 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 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 shutdownread() const; void shutdownwrite() const;
Shuts down one side of the connection.
void 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.
SOCKET socket_;
Contains the socket itself. No other state is stored in this class. All state information related to the socket is kept in the socket.
void clearError() const;
Sets the error code to no error. To make your application portable, use this function instead of the underlying OS specific function calls.
static void doRaise(int err, const char *funcName);
Throws an RWSocketError exception based on the value of the parameter err. Deprecated; you can refuse support for this function by defining the macro RW_DISABLE_DEPRECATED.
int lastError() const;
Returns the last error on this socket. To make your application portable, use this function instead of the underlying OS specific function calls.
void raise(const char *funcName) const; void raiseUnlessWouldBlock(const char *funcName) const;
Deprecated; use raise(const char*, int) or raiseUnlessWouldBlock(const char*, int) in conjunction with lastError(). You can refuse support for this function by defining the macro RW_DISABLE_DEPRECATED.
void raise(const char *funcName, int err) const;
Throws an RWSocketError exception based on the error code passed in the parameter.
void raiseUnlessWouldBlock(const char *funcName, int err) const;
Throws an RWSocketError exception based on the error code passed in the parameter.
ostream& operator<<(ostream& strm, const RWSocket& x);
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.
SET_BLOCKING(RWSocket)
Deprecated; use rwSetBlocking(). You can refuse support for this macro by defining the macro RW_DISABLE_DEPRECATED.
SET_NON_BLOCKING(RWSocket)
Deprecated; use rwSetNonBlocking(). You can refuse support for this macro by defining the macro RW_DISABLE_DEPRECATED.
© Copyright Rogue Wave Software, Inc. All Rights Reserved.
Rogue Wave and SourcePro are registered trademarks of Rogue Wave Software, Inc. in the United States and other countries. All other trademarks are the property of their respective owners.
Contact Rogue Wave about documentation or support issues.