Writing a Simple Client
Example 1 connects to a TCP/IP server, and then writes a message to the server. If this code does not run for you, read the next section, which gives an example of error handling.
Example 1 – Writing a simple client
#include <rw/rstream.h>
#include <rw/network/RWSocketPortal.h> //1
#include <rw/network/RWInetAddr.h> //2
#include <rw/network/RWWinSockInfo.h> //3
 
int main()
{
RWWinSockInfo info; //4
RWSocketPortal p( RWInetAddr(3010,"net.roguewave.com") ); //5
p.sendAtLeast("Hello out there!"); //6
return 0;
}
//1 Contains the declarations needed for the RWSocketPortal class.
//2 Declares the TCP/IP address classes, which are needed 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 Constructs a socket portal, which is connected to the Internet server on net.roguewave.com at port 3010. The constructor takes as a parameter a reference to the abstract base class RWSockAddrBase. Applications can build RWInetAddr objects in place and connect to the address specified by this object. This technique works because RWInetAddr is derived from RWSockAddrBase.
If you are not connected to the Internet, you can change this line so that it connects to a server that you can reach, such as port 7 or 9 (the echo discard servers) of UNIX or Windows machines. Your system or network administrator might be able to suggest a local server for experiments.
//6 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.
This example does not use RWPortal. Instead, it uses an RWPortal subclass, RWSocketPortal. Aside from the constructor, this example uses only member functions from the base class RWPortal. For more information about the relationship between RWPortal and RWSocketPortal, see Understanding the Portal and Implementation Classes. Most everything you learn about RWSocketPortal also applies to RWPortal.