Google

C++ Portable Types Library (PTypes) Version 1.7


Top: Networking: Examples

Example 1. This example demonstrates the basic usage of streaming network interfaces ipstream and ipstmserver. It consists of two separate programs: the test client and the test server. The server handles requests containing a single word "Hello" by sending a response greeting back to the client. This example would work for named pipes as well, i.e. if you replace the class names ipstream and ipstmserver with namedpipe and npserver and fix the construction parameters.

Client:

#include <pinet.h>

USING_PTYPES

const int testport = 8085;
const int maxtoken = 4096;

int main()
{
    // create a client socket and send a greeting to the server
    // assuming that the server is on the same host (127.0.0.1)

    ipstream client(ipaddress(127, 0, 0, 1), testport);

    try
    {
        client.open();

        pout.put("Sending a request to the server...\n");
        client.putline("Hello");
        client.flush();

        // receive the response
        string rsp = client.line(maxtoken);
        pout.putf("Received: %s\n", pconst(rsp));

        // need to close the socket explicitly to gracefully shutdown 
        // the peer host too. otherwise, ~ipstream() will call cancel()
        // and leave the peer in a waiting state (not forever though).
        client.close();
    }
    catch(estream* e)
    {
        perr.putf("Error: %s\n", pconst(e->get_message()));
        delete e;
    }

    return 0;
}

 

Server:

#include <ptime.h>
#include <pinet.h>

USING_PTYPES

const int testport = 8085;
const int maxtoken = 4096;

void servermain(ipstmserver& svr)
{
    ipstream client;

    pout.putf("Ready to answer queries on port %d\n", testport);

    while(true)
    {
        // serve() will wait for a connection request and will prepare
        // the supplied ipstream object for talking to the peer.
        // note that (unlikely) exceptions thrown in serve() will be 
        // caught in main()
        svr.serve(client);
        
        // for better performance the server would start a new thread
        // for each client request. for simplicity, we serve the request
        // in-place:
        if (client.get_active())
        {
            try
            {
                // read the request line:
                // real-world network applications should limit input data
                // to prevent potential denial-of-service attacks
                string req = lowercase(client.line(maxtoken));
                if (req == "hello")
                {
                    // try to reverse-lookup the client's IP
                    string host = phostbyaddr(client.get_ip());
                    if (isempty(host))
                        host = iptostring(client.get_ip());
                    
                    // now send our greeting to the client
                    client.putline("Hello, " + host + " ("
                        + iptostring(client.get_ip()) + "), nice to see you!");
                    client.flush();

                    // log this request
                    string timestamp = nowstring("%d-%b-%Y %H:%M:%S", false);
                    pout.putf("%s  greeting received from %s (%s)\n",
                        pconst(timestamp), pconst(host), pconst(iptostring(client.get_ip())));

                }

                client.close();
            }
            catch(estream* e)
            {
                perr.putf("Error: %s\n", pconst(e->get_message()));
                delete e;
            }
        }
    }
}

int main()
{
    ipstmserver svr;

    try
    {
        // bind to all local addresses on port 8085
        svr.bindall(testport);

        // enter an infinite loop of serving requests
        servermain(svr);
    }
    catch(estream* e)
    {
        perr.putf("FATAL: %s\n", pconst(e->get_message()));
        delete e;
    }

    return 0;
}

 

Example 2. This example demonstrates the use of message-oriented networking interfaces ipmessage and ipmsgserver. The client sends a broadcast message to the local network and waits for a response. It may retry the request several times.

Client:

#include <pinet.h>

USING_PTYPES

const int testport = 8085;
const int maxtoken = 4096;

const int tries = 3;
const int firsttimeout = 2000;


bool dorequest(int timeout)
{
    ipmessage msg(ipbcast, testport);

    try
    {
        pout.put("Broadcasting a request...\n");
        msg.send("Hello");

        // wait for a response the specified amount of time
        if (!msg.waitfor(timeout))
            return false;
        
        string rsp = msg.receive(maxtoken);
        pout.putf("Received: %s\n", pconst(rsp));

    }
    catch(estream* e)
    {
        perr.putf("Error: %s\n", pconst(e->get_message()));
        delete e;
    }
    
    return true;
}


int main()
{
    int timeout = firsttimeout;
    for (int i = 0; i < tries; i++)
    {
        if (dorequest(timeout))
            break;
        // double the timeout value
        timeout *= 2;
    }

    return 0;
}

 

Server:

#include <ptime.h>
#include <pinet.h>

USING_PTYPES

const int testport = 8085;
const int maxtoken = 4096;


void servermain(ipmsgserver& svr)
{
    pout.putf("Ready to answer queries on port %d\n", testport);

    bool quit = false;
    do
    {
        try
        {
            // receive the "hello" request and send a simple answer
            // back to the client
            string req = lowercase(svr.receive(maxtoken));
            if (req == "hello")
            {
                string host = svr.get_host();
                if (isempty(host))
                    host = iptostring(svr.get_ip());

                svr.send("Hello, " + host + " ("
                    + iptostring(svr.get_ip()) + "), nice to see you!");

                // log this request
                string timestamp = nowstring("%d-%b-%Y %H:%M:%S", false);
                pout.putf("%s  greeting received from %s (%s)\n",
                    pconst(timestamp), pconst(host), pconst(iptostring(svr.get_ip())));
            }
        }
        catch(estream* e)
        {
            perr.putf("Server error: %s\n", pconst(e->get_message()));
            delete e;
        }
        
    } while (!quit);
}


int main()
{
    ipmsgserver svr;

    try
    {
        svr.bindall(testport);

        // try to listen on socket once to generate an error right away,
        // before entering the main server loop
        svr.poll();

        // enter an infinite loop of serving requests
        servermain(svr);
    }
    catch(estream* e)
    {
        perr.putf("FATAL: %s\n", pconst(e->get_message()));
        delete e;
    }


    return 0;
}

See also: ipstream, ipstmserver, ipmessage, ipmsgserver, Utilities


PTypes home