// Shows how to connect to a server, and send and receive data.
//   Meant to be used with the simpleserver program.

#include "Dasyne.hpp"
#include <iostream>

using namespace std;
using namespace libdasyne;

//_______________ Static Variables _______________

//generates network events
DEngine netEngine;

//handles our connection to the server
DClient *client = new DClient(&netEngine);

//The port number to communicate over
const uint16_t PORT_NUMBER = 5127;

//False if we should stop the program
static bool runProgram = true;

//_______________ Event Handlers _______________

//Called when we connect to the server
void connectHandler(std::string netMessage,
                    NetworkCode socketStatus)
{
    DBuffer greeting;//a message to send to the server

    if (socketStatus == DA_SUCCESS)
    {
        cout << "Connected to " << client->getRemoteAddress() << endl;

        greeting.appendString("Hello, Server!");
        client->send(greeting);
    }//if socketStatus
    else
    {
        cout << netMessage << endl;
        runProgram = false;
    }//else socketStatus
}//connectHandler

//Called when we send all pending data
void sendHandler(void)
{
    cout << "Sent all data" << endl;
}//sendHandler

//Called when the server sends us data
void receiveHandler(DBuffer &theData)
{
    cout << "Received " << theData.toString() << endl;
    cout << "Disconnecting..." << endl;
    runProgram = false;
}//receiveHandler

//Called when an error occurs. If socketOK is false, the connection failed
void errorHandler(string errMsg,
                  bool socketOK)
{
    cout << errMsg << endl;
    if (!socketOK)
        runProgram = false;
}//errorHandler

//_______________ Main Function _______________

int main(int argc,
         char *argv[])
{
    int eventsRun = 0;//the number of events dispatched by a call to update()

    //### Verify that the proper number of arguments were given ###
    if (argc != 2)
    {
        cout << "Usage: simpleclient <host name>" << endl;
        cout << endl;
        runProgram = false;
    }//if argc

    //### Set up event handlers and connect to the server ###
    else
    {
        client->setReceiveHandler(&receiveHandler);
        client->setSendHandler(&sendHandler);
        client->setErrorHandler(&errorHandler);
        client->startConnect(argv[1], PORT_NUMBER, DA_IPV4, &connectHandler);
    }//else

    //### Run the event loop ###
    while (runProgram)
    {
        //Dispatch any queued events
        eventsRun = netEngine.update();
        if (eventsRun < 0)
        {
            cout << netEngine.getErrMsg() << endl;
            runProgram = false;
        }//if eventsRun

        //Sleep if we have nothing to do
        else if (eventsRun == 0)
            DEngine::sleep(1);
    }//while runProgram

    //### Delete the classes that use netEngine before deleting netEngine ###
    delete client;

    return 0;
}//main










Back to Contents