summaryrefslogtreecommitdiffstats
path: root/doc/html/clientserver-example.html
blob: 97547494ee061e3fc4e179378cb215a9c79b54fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- /home/espenr/tmp/qt-3.3.8-espenr-2499/qt-x11-free-3.3.8/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"><!--
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">TQSocket</a> class, and the server also uses
<a href="qserversocket.html">TQServerSocket</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.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 &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">TQSocket</a>
{
    <a href="metaobjects.html#Q_OBJECT">Q_OBJECT</a>
public:
    ClientSocket( int sock, TQObject *parent=0, const char *name=0 ) :
        <a href="qsocket.html">TQSocket</a>( parent, name )
    {
        line = 0;
        connect( this, SIGNAL(readyRead()),
                SLOT(readClient()) );
        connect( this, SIGNAL(connectionClosed()),
                SLOT(deleteLater()) );
        setSocket( sock );
    }

    ~ClientSocket()
    {
    }

signals:
    void logText( const <a href="qstring.html">TQString</a>&amp; );

private slots:
    void readClient()
    {
        <a href="qtextstream.html">TQTextStream</a> ts( this );
        while ( canReadLine() ) {
<a name="x787"></a>            <a href="qstring.html">TQString</a> str = ts.<a href="qtextstream.html#readLine">readLine</a>();
            emit logText( tr("Read: '%1'\n").arg(str) );

            ts &lt;&lt; line &lt;&lt; ": " &lt;&lt; str &lt;&lt; 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 <a href="qserversocket.html">TQServerSocket</a>
{
    Q_OBJECT
public:
    SimpleServer( <a href="qobject.html">TQObject</a>* parent=0 ) :
        <a href="qserversocket.html">TQServerSocket</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 )
    {
        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 <a href="qvbox.html">TQVBox</a>
{
    Q_OBJECT
public:
    ServerInfo()
    {
        SimpleServer *server = new SimpleServer( this );

        <a href="qstring.html">TQString</a> itext = tr(
                "This is a small server example.\n"
                "Connect with the client now."
                );
        <a href="qlabel.html">TQLabel</a> *lb = new <a href="qlabel.html">TQLabel</a>( itext, this );
<a name="x784"></a>        lb-&gt;<a href="qlabel.html#setAlignment">setAlignment</a>( AlignHCenter );
        infoText = new <a href="qtextview.html">TQTextView</a>( this );
        <a href="qpushbutton.html">TQPushButton</a> *tquit = new <a href="qpushbutton.html">TQPushButton</a>( tr("Quit") , this );

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

    ~ServerInfo()
    {
    }

private slots:
    void newConnect( ClientSocket *s )
    {
<a name="x786"></a>        infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("New connection\n") );
        connect( s, SIGNAL(logText(const <a href="qstring.html">TQString</a>&amp;)),
                infoText, SLOT(<a href="qtextedit.html#append">append</a>(const <a href="qstring.html">TQString</a>&amp;)) );
<a name="x785"></a>        connect( s, SIGNAL(<a href="qsocket.html#connectionClosed">connectionClosed</a>()),
                SLOT(connectionClosed()) );
    }

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

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


int main( int argc, char** argv )
{
    <a href="qapplication.html">TQApplication</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.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 &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">TQVBox</a>
{
    Q_OBJECT
public:
    Client( const <a href="qstring.html">TQString</a> &amp;host, Q_UINT16 port )
    {
        // GUI layout
        infoText = new <a href="qtextview.html">TQTextView</a>( this );
        <a href="qhbox.html">TQHBox</a> *hb = new <a href="qhbox.html">TQHBox</a>( this );
        inputText = new <a href="qlineedit.html">TQLineEdit</a>( hb );
        <a href="qpushbutton.html">TQPushButton</a> *send = new <a href="qpushbutton.html">TQPushButton</a>( tr("Send") , hb );
        <a href="qpushbutton.html">TQPushButton</a> *close = new <a href="qpushbutton.html">TQPushButton</a>( tr("Close connection") , this );
        <a href="qpushbutton.html">TQPushButton</a> *tquit = new <a href="qpushbutton.html">TQPushButton</a>( tr("Quit") , this );

<a name="x792"></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( tquit, SIGNAL(<a href="qbutton.html#clicked">clicked</a>()), qApp, SLOT(<a href="qapplication.html#tquit">tquit</a>()) );

        // create the socket and connect various of its signals
        socket = new <a href="qsocket.html">TQSocket</a>( this );
<a name="x798"></a>        connect( socket, SIGNAL(<a href="qsocket.html#connected">connected</a>()),
                SLOT(socketConnected()) );
<a name="x799"></a>        connect( socket, SIGNAL(<a href="qsocket.html#connectionClosed">connectionClosed</a>()),
                SLOT(socketConnectionClosed()) );
<a name="x803"></a>        connect( socket, SIGNAL(<a href="qsocket.html#readyRead">readyRead</a>()),
                SLOT(socketReadyRead()) );
<a name="x801"></a>        connect( socket, SIGNAL(<a href="qsocket.html#error">error</a>(int)),
                SLOT(socketError(int)) );

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

    ~Client()
    {
    }

private slots:
    void closeConnection()
    {
<a name="x796"></a>        socket-&gt;<a href="qsocket.html#close">close</a>();
<a name="x804"></a>        if ( socket-&gt;<a href="qsocket.html#state">state</a>() == TQSocket::Closing ) {
            // We have a delayed close.
<a name="x800"></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">TQTextStream</a> os(socket);
<a name="x794"></a>        os &lt;&lt; inputText-&gt;<a href="qlineedit.html#text">text</a>() &lt;&lt; "\n";
<a name="x793"></a>        inputText-&gt;<a href="qlineedit.html#setText">setText</a>( "" );
    }

    void socketReadyRead()
    {
        // read from the server
<a name="x795"></a>        while ( socket-&gt;<a href="qsocket.html#canReadLine">canReadLine</a>() ) {
<a name="x802"></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">TQSocket</a> *socket;
    <a href="qtextview.html">TQTextView</a> *infoText;
    <a href="qlineedit.html">TQLineEdit</a> *inputText;
};


int main( int argc, char** argv )
{
    <a href="qapplication.html">TQApplication</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; 2007
<a href="troll.html">Trolltech</a><td align=center><a href="trademarks.html">Trademarks</a>
<td align=right><div align=right>TQt 3.3.8</div>
</table></div></address></body>
</html>