Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

An Iostream-Compatible Socket Wrapper


December 2001/An Iostream-Compatible Socket Wrapper/Listing 7

Listing 7: Simple test server program

#include "Sockets.h"
#include <iostream>
#include <string>
#include <complex>

using namespace std;

const int IPportnumber = 12345;

int main()
{
    string message("Hello Socket!");
    complex<double> cplx(1.0, 2.0);
    int integer(1234);

    if (socketsInit() == false)
    {
        cout << "cannot initialize sockets" << endl;
        return 0;
    }

    try
    {
        TCPSocketWrapper sockserver;

        // listen on some port
        sockserver.listen(IPportnumber);

        cout << "server is ready" << endl;

        // accept connection from client
        TCPSocketWrapper sock(sockserver.accept());

        cout << "accepted connection from: "
            << sock.address() << endl;

        // make the stream around the socket wrapper
        TCPStream stream(sock);

        bool oncemore = true;
        int command;
        while (oncemore)
        {
            // read the command
            stream >> command;
            switch (command)
            {
            case 1:
                cout << "command 1" << endl;
                stream << message << endl;
                break;
            case 2:
                cout << "command 2" << endl;
                stream << integer << endl;
                break;
            case 3:
                cout << "command 3" << endl;
                stream << cplx << endl;
                break;
            default:
                cout << "END command" << endl;
                oncemore = false;
                break;
            }
        }
    }
    catch (const SocketRunTimeException &e)
    {
        cout << "socket exception: "
            << e.what() << endl;
    }

    socketsEnd();

    return 0;
}
— End of Listing —

Related Reading


More Insights