Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions

A small client-server example

This example shows how two programs can communicate using sockets.

Two simple example programs are provided, a client program and a server program. Both use the TQSocket class, and the server also uses TQServerSocket class.

The server listens on port number 4242 and accepts incoming connections. It sends back every line it receives from the client, prepended with the line number.

The client tries to connect to the server on the host specified on the command line or to localhost if no command line arguments are specified. You can send single lines to the server.


Implementation server (server.cpp):

/****************************************************************************
** $Id: qt/server.cpp   3.3.8   edited Jan 11 14:37 $
**
** Copyright (C) 1992-2007 Trolltech ASA.  All rights reserved.
**
** This file is part of an example program for TQt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <ntqsocket.h>
#include <ntqserversocket.h>
#include <ntqapplication.h>
#include <ntqvbox.h>
#include <ntqtextview.h>
#include <ntqlabel.h>
#include <ntqpushbutton.h>
#include <ntqtextstream.h>

#include <stdlib.h>


/*
  The ClientSocket class provides a socket that is connected with a client.
  For every client that connects to the server, the server creates a new
  instance of this class.
*/
class ClientSocket : public TQSocket
{
    TQ_OBJECT
public:
    ClientSocket( int sock, TQObject *parent=0, const char *name=0 ) :
        TQSocket( parent, name )
    {
        line = 0;
        connect( this, TQ_SIGNAL(readyRead()),
                TQ_SLOT(readClient()) );
        connect( this, TQ_SIGNAL(connectionClosed()),
                TQ_SLOT(deleteLater()) );
        setSocket( sock );
    }

    ~ClientSocket()
    {
    }

signals:
    void logText( const TQString& );

private slots:
    void readClient()
    {
        TQTextStream ts( this );
        while ( canReadLine() ) {
            TQString str = ts.readLine();
            emit logText( tr("Read: '%1'\n").arg(str) );

            ts << line << ": " << str << endl;
            emit logText( tr("Wrote: '%1: %2'\n").arg(line).arg(str) );

            line++;
        }
    }

private:
    int line;
};


/*
  The SimpleServer class handles new connections to the server. For every
  client that connects, it creates a new ClientSocket -- that instance is now
  responsible for the communication with that client.
*/
class SimpleServer : public TQServerSocket
{
    TQ_OBJECT
public:
    SimpleServer( TQObject* parent=0 ) :
        TQServerSocket( 4242, 1, parent )
    {
        if ( !ok() ) {
            tqWarning("Failed to bind to port 4242");
            exit(1);
        }
    }

    ~SimpleServer()
    {
    }

    void newConnection( int socket )
    {
        ClientSocket *s = new ClientSocket( socket, this );
        emit newConnect( s );
    }

signals:
    void newConnect( ClientSocket* );
};


/*
  The ServerInfo class provides a small GUI for the server. It also creates the
  SimpleServer and as a result the server.
*/
class ServerInfo : public TQVBox
{
    TQ_OBJECT
public:
    ServerInfo()
    {
        SimpleServer *server = new SimpleServer( this );

        TQString itext = tr(
                "This is a small server example.\n"
                "Connect with the client now."
                );
        TQLabel *lb = new TQLabel( itext, this );
        lb->setAlignment( AlignHCenter );
        infoText = new TQTextView( this );
        TQPushButton *quit = new TQPushButton( tr("Quit") , this );

        connect( server, TQ_SIGNAL(newConnect(ClientSocket*)),
                TQ_SLOT(newConnect(ClientSocket*)) );
        connect( quit, TQ_SIGNAL(clicked()), tqApp,
                TQ_SLOT(quit()) );
    }

    ~ServerInfo()
    {
    }

private slots:
    void newConnect( ClientSocket *s )
    {
        infoText->append( tr("New connection\n") );
        connect( s, TQ_SIGNAL(logText(const TQString&)),
                infoText, TQ_SLOT(append(const TQString&)) );
        connect( s, TQ_SIGNAL(connectionClosed()),
                TQ_SLOT(connectionClosed()) );
    }

    void connectionClosed()
    {
        infoText->append( tr("Client closed connection\n") );
    }

private:
    TQTextView *infoText;
};


int main( int argc, char** argv )
{
    TQApplication app( argc, argv );
    ServerInfo info;
    app.setMainWidget( &info );
    info.show();
    return app.exec();
}

#include "server.moc"


Implementation client (client.cpp):

/****************************************************************************
** $Id: qt/client.cpp   3.3.8   edited Jan 11 14:37 $
**
** Copyright (C) 1992-2007 Trolltech ASA.  All rights reserved.
**
** This file is part of an example program for TQt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <ntqsocket.h>
#include <ntqapplication.h>
#include <ntqvbox.h>
#include <ntqhbox.h>
#include <ntqtextview.h>
#include <ntqlineedit.h>
#include <ntqlabel.h>
#include <ntqpushbutton.h>
#include <ntqtextstream.h>


class Client : public TQVBox
{
    TQ_OBJECT
public:
    Client( const TQString &host, TQ_UINT16 port )
    {
        // GUI layout
        infoText = new TQTextView( this );
        TQHBox *hb = new TQHBox( this );
        inputText = new TQLineEdit( hb );
        TQPushButton *send = new TQPushButton( tr("Send") , hb );
        TQPushButton *close = new TQPushButton( tr("Close connection") , this );
        TQPushButton *quit = new TQPushButton( tr("Quit") , this );

        connect( send, TQ_SIGNAL(clicked()), TQ_SLOT(sendToServer()) );
        connect( close, TQ_SIGNAL(clicked()), TQ_SLOT(closeConnection()) );
        connect( quit, TQ_SIGNAL(clicked()), tqApp, TQ_SLOT(quit()) );

        // create the socket and connect various of its signals
        socket = new TQSocket( this );
        connect( socket, TQ_SIGNAL(connected()),
                TQ_SLOT(socketConnected()) );
        connect( socket, TQ_SIGNAL(connectionClosed()),
                TQ_SLOT(socketConnectionClosed()) );
        connect( socket, TQ_SIGNAL(readyRead()),
                TQ_SLOT(socketReadyRead()) );
        connect( socket, TQ_SIGNAL(error(int)),
                TQ_SLOT(socketError(int)) );

        // connect to the server
        infoText->append( tr("Trying to connect to the server\n") );
        socket->connectToHost( host, port );
    }

    ~Client()
    {
    }

private slots:
    void closeConnection()
    {
        socket->close();
        if ( socket->state() == TQSocket::Closing ) {
            // We have a delayed close.
            connect( socket, TQ_SIGNAL(delayedCloseFinished()),
                    TQ_SLOT(socketClosed()) );
        } else {
            // The socket is closed.
            socketClosed();
        }
    }

    void sendToServer()
    {
        // write to the server
        TQTextStream os(socket);
        os << inputText->text() << "\n";
        inputText->setText( "" );
    }

    void socketReadyRead()
    {
        // read from the server
        while ( socket->canReadLine() ) {
            infoText->append( socket->readLine() );
        }
    }

    void socketConnected()
    {
        infoText->append( tr("Connected to server\n") );
    }

    void socketConnectionClosed()
    {
        infoText->append( tr("Connection closed by the server\n") );
    }

    void socketClosed()
    {
        infoText->append( tr("Connection closed\n") );
    }

    void socketError( int e )
    {
        infoText->append( tr("Error number %1 occurred\n").arg(e) );
    }

private:
    TQSocket *socket;
    TQTextView *infoText;
    TQLineEdit *inputText;
};


int main( int argc, char** argv )
{
    TQApplication app( argc, argv );
    Client client( argc<2 ? "localhost" : argv[1], 4242 );
    app.setMainWidget( &client );
    client.show();
    return app.exec();
}

#include "client.moc"

See also Network Examples.


Copyright © 2007 TrolltechTrademarks
TQt 3.3.8