Using RWSocket
The Berkeley sockets adapter is represented by the RWSocket class. Each socket API function has a corresponding RWSocket member function. In addition, RWSocket member functions include:
*Strong typing, which lets you catch errors at compile time
*Default arguments, which make common usage easier
*Errors that are indicated by using exceptions—you do not have to check returns codes
*Simplified pass and return of socket addresses
*Encapsulation and overloading, which coalesce multiple socket calls into one call
For example, you can set up a server with a single call to listen()—you do not have to call socket() and bind() first.
Example 13 connects to a socket and sends it a line of output, without error handling.
Example 13 – Connecting to a socket
#include <rw/rstream.h>
#include <rw/network/RWSocket.h> //1
#include <rw/network/RWInetAddr.h> //2
#include <rw/network/RWWinSockInfo.h> //3
 
int main()
{
RWWinSockInfo info; //4
RWSocket p; //5
p.connect( RWInetAddr(3010,"net.roguewave.com") ); //6
p.sendAtLeast("Hello out there!"); //7
p.closesocket(); //8
return 0;
}
//1 Includes the declarations needed for the RWSocket class.
//2 Declares the TCP/IP address classes, which are necessary to connect to Internet servers.
//3 Includes declarations needed for using the Winsock DLL. On the UNIX operating system, this file does nothing, but including it increases code portability.
//4 Initializes the Winsock DLL. Defining an instance of the RWWinSockInfo class in a scope contains the use of the Networking package. For more information, see Initializing and Cleaning Up.
Under UNIX, this line does nothing, but it is a good idea to include an RWWinSockInfo object where appropriate, in case your code is ported to Windows.
//5 Defines a socket object. The socket needs to be initialized using a call to one of the member functions socket(), bind(), connect(), or listen() before it can be used.
//6 Connects the socket to the Internet server on net.roguewave.com at port 3010.
//7 Sends a message to the server. Several member functions send data. Your choice depends on the format of the information and whether or not it is acceptable to send only part of the data. The sendAtLeast() member function calls the underlying communication system’s send() function until all data is sent.
//8 Closes down the socket. This frees up any system resources used by the socket. If copies of the socket have been created using the copy constructor or assignment operator, those copies become invalid. If you try to use them, an exception is thrown.