Sophie

Sophie

distrib > Mandriva > 8.2 > i586 > media > contrib > by-pkgid > 112b0974ad288f6cd55bf971ee6026a9 > files > 635

libqt3-devel-3.0.2-2mdk.i586.rpm

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- /tmp/qt-3.0-reggie-28534/qt-x11-free-3.0.2/examples/network/clientserver/clientserver.doc:5 -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>A small client-server example</title>
<style type="text/css"><!--
h3.fn,span.fn { margin-left: 1cm; text-indent: -1cm; }
a:link { color: #004faf; text-decoration: none }
a:visited { color: #672967; text-decoration: none }
body { background: #ffffff; color: black; }
--></style>
</head>
<body>

<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr bgcolor="#E5E5E5">
<td valign=center>
 <a href="index.html">
<font color="#004faf">Home</font></a>
 | <a href="classes.html">
<font color="#004faf">All&nbsp;Classes</font></a>
 | <a href="mainclasses.html">
<font color="#004faf">Main&nbsp;Classes</font></a>
 | <a href="annotated.html">
<font color="#004faf">Annotated</font></a>
 | <a href="groups.html">
<font color="#004faf">Grouped&nbsp;Classes</font></a>
 | <a href="functions.html">
<font color="#004faf">Functions</font></a>
</td>
<td align="right" valign="center"><img src="logo32.png" align="right" width="64" height="32" border="0"></td></tr></table><h1 align=center>A small client-server example</h1>

 
<p> 
<p> This example shows how two programs can communicate using sockets.
<p> Two simple example programs are provided, a client program and a
server program. Both use the <a href="qsocket.html">QSocket</a> class, and the server also uses
<a href="qserversocket.html">QServerSocket</a> class.
<p> 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.
<p> 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.
<p> <hr>
<p> Implementation server (server.cpp):
<p> <pre>/****************************************************************************
** $Id:  qt/server.cpp   3.0.2   edited Oct 12 12:18 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include &lt;<a href="qsocket-h.html">qsocket.h</a>&gt;
#include &lt;<a href="qserversocket-h.html">qserversocket.h</a>&gt;
#include &lt;<a href="qapplication-h.html">qapplication.h</a>&gt;
#include &lt;<a href="qvbox-h.html">qvbox.h</a>&gt;
#include &lt;<a href="qtextview-h.html">qtextview.h</a>&gt;
#include &lt;<a href="qlabel-h.html">qlabel.h</a>&gt;
#include &lt;<a href="qpushbutton-h.html">qpushbutton.h</a>&gt;
#include &lt;<a href="qtextstream-h.html">qtextstream.h</a>&gt;

#include &lt;stdlib.h&gt;


/*
  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 <a href="qsocket.html">QSocket</a>
{
    <a href="metaobjects.html#Q_OBJECT">Q_OBJECT</a>
public:
    ClientSocket( int sock, QObject *parent=0, const char *name=0 ) :
        <a href="qsocket.html">QSocket</a>( parent, name )
    {
        line = 0;
        connect( this, SIGNAL(readyRead()), SLOT(readClient()) );
        connect( this, SIGNAL(connectionClosed()), SLOT(connectionClosed()) );
        setSocket( sock );
    }

    ~ClientSocket()
    {
    }

private slots:
    void readClient()
    {
        while ( canReadLine() ) {
            <a href="qtextstream.html">QTextStream</a> os( this );
            os &lt;&lt; line &lt;&lt; ": " &lt;&lt; readLine();
            line++;
        }
    }

    void connectionClosed()
    {
        delete this;
    }

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 <a href="qserversocket.html">QServerSocket</a>
{
    Q_OBJECT
public:
    SimpleServer( <a href="qobject.html">QObject</a>* parent=0 ) :
        <a href="qserversocket.html">QServerSocket</a>( 4242, 1, parent )
    {
        if ( !ok() ) {
            <a href="qapplication.html#qWarning">qWarning</a>("Failed to bind to port 4242");
            exit(1);
        }
    }

    ~SimpleServer()
    {
    }

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

signals:
    void newConnect();
};


/*
  The ServerInfo class provides a small GUI for the server. It also creates the
  SimpleServer and as a result the server.
*/
class ServerInfo : public <a href="qvbox.html">QVBox</a>
{
    Q_OBJECT
public:
    ServerInfo()
    {
        SimpleServer *server = new SimpleServer( this );

        <a href="qstring.html">QString</a> itext = QString(
                "This is a small server example.\n"
                "Connect with the client now."
                );
        <a href="qlabel.html">QLabel</a> *lb = new <a href="qlabel.html">QLabel</a>( itext, this );
<a name="x1056"></a>        lb-&gt;<a href="qlabel.html#setAlignment">setAlignment</a>( AlignHCenter );
        infoText = new <a href="qtextview.html">QTextView</a>( this );
        <a href="qpushbutton.html">QPushButton</a> *quit = new <a href="qpushbutton.html">QPushButton</a>( "Quit" , this );

        connect( server, SIGNAL(newConnect()), SLOT(newConnect()) );
        connect( quit, SIGNAL(<a href="qbutton.html#clicked">clicked</a>()), qApp, SLOT(<a href="qapplication.html#quit">quit</a>()) );
    }

    ~ServerInfo()
    {
    }

private slots:
    void newConnect()
    {
<a name="x1057"></a>        infoText-&gt;<a href="qtextedit.html#append">append</a>( "New connection\n" );
    }

private:
    <a href="qtextview.html">QTextView</a> *infoText;
};


int main( int argc, char** argv )
{
    <a href="qapplication.html">QApplication</a> app( argc, argv );
    ServerInfo info;
    app.<a href="qapplication.html#setMainWidget">setMainWidget</a>( &amp;info );
    info.<a href="qwidget.html#show">show</a>();
    return app.<a href="qapplication.html#exec">exec</a>();
}

#include "server.moc"
</pre>

<p> <hr>
<p> Implementation client (client.cpp):
<p> <pre>/****************************************************************************
** $Id:  qt/client.cpp   3.0.2   edited Nov 5 19:12 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include &lt;<a href="qsocket-h.html">qsocket.h</a>&gt;
#include &lt;<a href="qapplication-h.html">qapplication.h</a>&gt;
#include &lt;<a href="qvbox-h.html">qvbox.h</a>&gt;
#include &lt;<a href="qhbox-h.html">qhbox.h</a>&gt;
#include &lt;<a href="qtextview-h.html">qtextview.h</a>&gt;
#include &lt;<a href="qlineedit-h.html">qlineedit.h</a>&gt;
#include &lt;<a href="qlabel-h.html">qlabel.h</a>&gt;
#include &lt;<a href="qpushbutton-h.html">qpushbutton.h</a>&gt;
#include &lt;<a href="qtextstream-h.html">qtextstream.h</a>&gt;


class Client : public <a href="qvbox.html">QVBox</a>
{
    Q_OBJECT
public:
    Client( const <a href="qstring.html">QString</a> &amp;host, Q_UINT16 port )
    {
        // GUI layout
        infoText = new <a href="qtextview.html">QTextView</a>( this );
        <a href="qhbox.html">QHBox</a> *hb = new <a href="qhbox.html">QHBox</a>( this );
        inputText = new <a href="qlineedit.html">QLineEdit</a>( hb );
        <a href="qpushbutton.html">QPushButton</a> *send = new <a href="qpushbutton.html">QPushButton</a>( tr("Send") , hb );
        <a href="qpushbutton.html">QPushButton</a> *close = new <a href="qpushbutton.html">QPushButton</a>( tr("Close connection") , this );
        <a href="qpushbutton.html">QPushButton</a> *quit = new <a href="qpushbutton.html">QPushButton</a>( tr("Quit") , this );

<a name="x1062"></a>        connect( send, SIGNAL(<a href="qbutton.html#clicked">clicked</a>()), SLOT(sendToServer()) );
        connect( close, SIGNAL(<a href="qbutton.html#clicked">clicked</a>()), SLOT(closeConnection()) );
        connect( quit, SIGNAL(<a href="qbutton.html#clicked">clicked</a>()), qApp, SLOT(<a href="qapplication.html#quit">quit</a>()) );

        // create the socket and connect various of its signals
        socket = new <a href="qsocket.html">QSocket</a>( this );
<a name="x1069"></a>        connect( socket, SIGNAL(<a href="qsocket.html#connected">connected</a>()),
                SLOT(socketConnected()) );
<a name="x1070"></a>        connect( socket, SIGNAL(<a href="qsocket.html#connectionClosed">connectionClosed</a>()),
                SLOT(socketConnectionClosed()) );
<a name="x1073"></a>        connect( socket, SIGNAL(<a href="qsocket.html#readyRead">readyRead</a>()),
                SLOT(socketReadyRead()) );
<a name="x1072"></a>        connect( socket, SIGNAL(<a href="qsocket.html#error">error</a>(int)),
                SLOT(socketError(int)) );

        // connect to the server
<a name="x1075"></a>        infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("Trying to connect to the server\n") );
<a name="x1068"></a>        socket-&gt;<a href="qsocket.html#connectToHost">connectToHost</a>( host, port );
    }

    ~Client()
    {
    }

private slots:
    void closeConnection()
    {
<a name="x1067"></a>        socket-&gt;<a href="qsocket.html#close">close</a>();
<a name="x1074"></a>        if ( socket-&gt;<a href="qsocket.html#state">state</a>() == QSocket::Closing ) {
            // We have a delayed close.
<a name="x1071"></a>            connect( socket, SIGNAL(<a href="qsocket.html#delayedCloseFinished">delayedCloseFinished</a>()),
                    SLOT(socketClosed()) );
        } else {
            // The socket is closed.
            socketClosed();
        }
    }

    void sendToServer()
    {
        // write to the server
        <a href="qtextstream.html">QTextStream</a> os(socket);
<a name="x1065"></a>        os &lt;&lt; inputText-&gt;<a href="qlineedit.html#text">text</a>() &lt;&lt; "\n";
<a name="x1064"></a>        inputText-&gt;<a href="qlineedit.html#setText">setText</a>( "" );
    }

    void socketReadyRead()
    {
        // read from the server
<a name="x1066"></a>        while ( socket-&gt;<a href="qsocket.html#canReadLine">canReadLine</a>() ) {
<a name="x1063"></a>            infoText-&gt;<a href="qtextedit.html#append">append</a>( socket-&gt;<a href="qsocket.html#readLine">readLine</a>() );
        }
    }

    void socketConnected()
    {
        infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("Connected to server\n") );
    }

    void socketConnectionClosed()
    {
        infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("Connection closed by the server\n") );
    }

    void socketClosed()
    {
        infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("Connection closed\n") );
    }

    void socketError( int e )
    {
        infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("Error number %1 occurred\n").arg(e) );
    }

private:
    <a href="qsocket.html">QSocket</a> *socket;
    <a href="qtextview.html">QTextView</a> *infoText;
    <a href="qlineedit.html">QLineEdit</a> *inputText;
};


int main( int argc, char** argv )
{
    <a href="qapplication.html">QApplication</a> app( argc, argv );
    Client client( argc&lt;2 ? "localhost" : argv[1], 4242 );
    app.<a href="qapplication.html#setMainWidget">setMainWidget</a>( &amp;client );
    client.<a href="qwidget.html#show">show</a>();
    return app.<a href="qapplication.html#exec">exec</a>();
}

#include "client.moc"
</pre>

<p>See also <a href="network-examples.html">Network Examples</a>.

<!-- eof -->
<p><address><hr><div align=center>
<table width=100% cellspacing=0 border=0><tr>
<td>Copyright &copy; 2001 
<a href="http://www.trolltech.com">Trolltech</a><td><a href="http://www.trolltech.com/trademarks.html">Trademarks</a>
<td align=right><div align=right>Qt version 3.0.2</div>
</table></div></address></body>
</html>