source: trunk/doc/html/clientserver-example.html

Last change on this file was 190, checked in by rudi, 14 years ago

reference documentation added

File size: 13.3 KB
RevLine 
[190]1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<!-- /home/espenr/tmp/qt-3.3.8-espenr-2499/qt-x11-free-3.3.8/examples/network/clientserver/clientserver.doc:5 -->
3<html>
4<head>
5<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
6<title>A small client-server example</title>
7<style type="text/css"><!--
8fn { margin-left: 1cm; text-indent: -1cm; }
9a:link { color: #004faf; text-decoration: none }
10a:visited { color: #672967; text-decoration: none }
11body { background: #ffffff; color: black; }
12--></style>
13</head>
14<body>
15
16<table border="0" cellpadding="0" cellspacing="0" width="100%">
17<tr bgcolor="#E5E5E5">
18<td valign=center>
19 <a href="index.html">
20<font color="#004faf">Home</font></a>
21 | <a href="classes.html">
22<font color="#004faf">All&nbsp;Classes</font></a>
23 | <a href="mainclasses.html">
24<font color="#004faf">Main&nbsp;Classes</font></a>
25 | <a href="annotated.html">
26<font color="#004faf">Annotated</font></a>
27 | <a href="groups.html">
28<font color="#004faf">Grouped&nbsp;Classes</font></a>
29 | <a href="functions.html">
30<font color="#004faf">Functions</font></a>
31</td>
32<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>
33
34
35<p>
36<p> This example shows how two programs can communicate using sockets.
37<p> Two simple example programs are provided, a client program and a
38server program. Both use the <a href="qsocket.html">QSocket</a> class, and the server also uses
39<a href="qserversocket.html">QServerSocket</a> class.
40<p> The server listens on port number 4242 and accepts incoming connections.
41It sends back every line it receives from the client, prepended with
42the line number.
43<p> The client tries to connect to the server on the host specified on the
44command line or to localhost if no command line arguments are
45specified. You can send single lines to the server.
46<p> <hr>
47<p> Implementation server (server.cpp):
48<p> <pre>/****************************************************************************
49** $Id: clientserver-example.html 2051 2007-02-21 10:04:20Z chehrlic $
50**
51** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.
52**
53** This file is part of an example program for Qt. This example
54** program may be used, distributed and modified without limitation.
55**
56*****************************************************************************/
57
58#include &lt;<a href="qsocket-h.html">qsocket.h</a>&gt;
59#include &lt;<a href="qserversocket-h.html">qserversocket.h</a>&gt;
60#include &lt;<a href="qapplication-h.html">qapplication.h</a>&gt;
61#include &lt;<a href="qvbox-h.html">qvbox.h</a>&gt;
62#include &lt;<a href="qtextview-h.html">qtextview.h</a>&gt;
63#include &lt;<a href="qlabel-h.html">qlabel.h</a>&gt;
64#include &lt;<a href="qpushbutton-h.html">qpushbutton.h</a>&gt;
65#include &lt;<a href="qtextstream-h.html">qtextstream.h</a>&gt;
66
67#include &lt;stdlib.h&gt;
68
69
70/*
71 The ClientSocket class provides a socket that is connected with a client.
72 For every client that connects to the server, the server creates a new
73 instance of this class.
74*/
75class ClientSocket : public <a href="qsocket.html">QSocket</a>
76{
77 <a href="metaobjects.html#Q_OBJECT">Q_OBJECT</a>
78public:
79 ClientSocket( int sock, QObject *parent=0, const char *name=0 ) :
80 <a href="qsocket.html">QSocket</a>( parent, name )
81 {
82 line = 0;
83 connect( this, SIGNAL(readyRead()),
84 SLOT(readClient()) );
85 connect( this, SIGNAL(connectionClosed()),
86 SLOT(deleteLater()) );
87 setSocket( sock );
88 }
89
90 ~ClientSocket()
91 {
92 }
93
94signals:
95 void logText( const <a href="qstring.html">QString</a>&amp; );
96
97private slots:
98 void readClient()
99 {
100 <a href="qtextstream.html">QTextStream</a> ts( this );
101 while ( canReadLine() ) {
102<a name="x787"></a> <a href="qstring.html">QString</a> str = ts.<a href="qtextstream.html#readLine">readLine</a>();
103 emit logText( tr("Read: '%1'\n").arg(str) );
104
105 ts &lt;&lt; line &lt;&lt; ": " &lt;&lt; str &lt;&lt; endl;
106 emit logText( tr("Wrote: '%1: %2'\n").arg(line).arg(str) );
107
108 line++;
109 }
110 }
111
112private:
113 int line;
114};
115
116
117/*
118 The SimpleServer class handles new connections to the server. For every
119 client that connects, it creates a new ClientSocket -- that instance is now
120 responsible for the communication with that client.
121*/
122class SimpleServer : public <a href="qserversocket.html">QServerSocket</a>
123{
124 Q_OBJECT
125public:
126 SimpleServer( <a href="qobject.html">QObject</a>* parent=0 ) :
127 <a href="qserversocket.html">QServerSocket</a>( 4242, 1, parent )
128 {
129 if ( !ok() ) {
130 <a href="qapplication.html#qWarning">qWarning</a>("Failed to bind to port 4242");
131 exit(1);
132 }
133 }
134
135 ~SimpleServer()
136 {
137 }
138
139 void newConnection( int socket )
140 {
141 ClientSocket *s = new ClientSocket( socket, this );
142 emit newConnect( s );
143 }
144
145signals:
146 void newConnect( ClientSocket* );
147};
148
149
150/*
151 The ServerInfo class provides a small GUI for the server. It also creates the
152 SimpleServer and as a result the server.
153*/
154class ServerInfo : public <a href="qvbox.html">QVBox</a>
155{
156 Q_OBJECT
157public:
158 ServerInfo()
159 {
160 SimpleServer *server = new SimpleServer( this );
161
162 <a href="qstring.html">QString</a> itext = tr(
163 "This is a small server example.\n"
164 "Connect with the client now."
165 );
166 <a href="qlabel.html">QLabel</a> *lb = new <a href="qlabel.html">QLabel</a>( itext, this );
167<a name="x784"></a> lb-&gt;<a href="qlabel.html#setAlignment">setAlignment</a>( AlignHCenter );
168 infoText = new <a href="qtextview.html">QTextView</a>( this );
169 <a href="qpushbutton.html">QPushButton</a> *quit = new <a href="qpushbutton.html">QPushButton</a>( tr("Quit") , this );
170
171 connect( server, SIGNAL(newConnect(ClientSocket*)),
172 SLOT(newConnect(ClientSocket*)) );
173 connect( quit, SIGNAL(<a href="qbutton.html#clicked">clicked</a>()), qApp,
174 SLOT(<a href="qapplication.html#quit">quit</a>()) );
175 }
176
177 ~ServerInfo()
178 {
179 }
180
181private slots:
182 void newConnect( ClientSocket *s )
183 {
184<a name="x786"></a> infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("New connection\n") );
185 connect( s, SIGNAL(logText(const <a href="qstring.html">QString</a>&amp;)),
186 infoText, SLOT(<a href="qtextedit.html#append">append</a>(const <a href="qstring.html">QString</a>&amp;)) );
187<a name="x785"></a> connect( s, SIGNAL(<a href="qsocket.html#connectionClosed">connectionClosed</a>()),
188 SLOT(connectionClosed()) );
189 }
190
191 void connectionClosed()
192 {
193 infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("Client closed connection\n") );
194 }
195
196private:
197 <a href="qtextview.html">QTextView</a> *infoText;
198};
199
200
201int main( int argc, char** argv )
202{
203 <a href="qapplication.html">QApplication</a> app( argc, argv );
204 ServerInfo info;
205 app.<a href="qapplication.html#setMainWidget">setMainWidget</a>( &amp;info );
206 info.<a href="qwidget.html#show">show</a>();
207 return app.<a href="qapplication.html#exec">exec</a>();
208}
209
210#include "server.moc"
211</pre>
212
213<p> <hr>
214<p> Implementation client (client.cpp):
215<p> <pre>/****************************************************************************
216** $Id: clientserver-example.html 2051 2007-02-21 10:04:20Z chehrlic $
217**
218** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.
219**
220** This file is part of an example program for Qt. This example
221** program may be used, distributed and modified without limitation.
222**
223*****************************************************************************/
224
225#include &lt;<a href="qsocket-h.html">qsocket.h</a>&gt;
226#include &lt;<a href="qapplication-h.html">qapplication.h</a>&gt;
227#include &lt;<a href="qvbox-h.html">qvbox.h</a>&gt;
228#include &lt;<a href="qhbox-h.html">qhbox.h</a>&gt;
229#include &lt;<a href="qtextview-h.html">qtextview.h</a>&gt;
230#include &lt;<a href="qlineedit-h.html">qlineedit.h</a>&gt;
231#include &lt;<a href="qlabel-h.html">qlabel.h</a>&gt;
232#include &lt;<a href="qpushbutton-h.html">qpushbutton.h</a>&gt;
233#include &lt;<a href="qtextstream-h.html">qtextstream.h</a>&gt;
234
235
236class Client : public <a href="qvbox.html">QVBox</a>
237{
238 Q_OBJECT
239public:
240 Client( const <a href="qstring.html">QString</a> &amp;host, Q_UINT16 port )
241 {
242 // GUI layout
243 infoText = new <a href="qtextview.html">QTextView</a>( this );
244 <a href="qhbox.html">QHBox</a> *hb = new <a href="qhbox.html">QHBox</a>( this );
245 inputText = new <a href="qlineedit.html">QLineEdit</a>( hb );
246 <a href="qpushbutton.html">QPushButton</a> *send = new <a href="qpushbutton.html">QPushButton</a>( tr("Send") , hb );
247 <a href="qpushbutton.html">QPushButton</a> *close = new <a href="qpushbutton.html">QPushButton</a>( tr("Close connection") , this );
248 <a href="qpushbutton.html">QPushButton</a> *quit = new <a href="qpushbutton.html">QPushButton</a>( tr("Quit") , this );
249
250<a name="x792"></a> connect( send, SIGNAL(<a href="qbutton.html#clicked">clicked</a>()), SLOT(sendToServer()) );
251 connect( close, SIGNAL(<a href="qbutton.html#clicked">clicked</a>()), SLOT(closeConnection()) );
252 connect( quit, SIGNAL(<a href="qbutton.html#clicked">clicked</a>()), qApp, SLOT(<a href="qapplication.html#quit">quit</a>()) );
253
254 // create the socket and connect various of its signals
255 socket = new <a href="qsocket.html">QSocket</a>( this );
256<a name="x798"></a> connect( socket, SIGNAL(<a href="qsocket.html#connected">connected</a>()),
257 SLOT(socketConnected()) );
258<a name="x799"></a> connect( socket, SIGNAL(<a href="qsocket.html#connectionClosed">connectionClosed</a>()),
259 SLOT(socketConnectionClosed()) );
260<a name="x803"></a> connect( socket, SIGNAL(<a href="qsocket.html#readyRead">readyRead</a>()),
261 SLOT(socketReadyRead()) );
262<a name="x801"></a> connect( socket, SIGNAL(<a href="qsocket.html#error">error</a>(int)),
263 SLOT(socketError(int)) );
264
265 // connect to the server
266<a name="x805"></a> infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("Trying to connect to the server\n") );
267<a name="x797"></a> socket-&gt;<a href="qsocket.html#connectToHost">connectToHost</a>( host, port );
268 }
269
270 ~Client()
271 {
272 }
273
274private slots:
275 void closeConnection()
276 {
277<a name="x796"></a> socket-&gt;<a href="qsocket.html#close">close</a>();
278<a name="x804"></a> if ( socket-&gt;<a href="qsocket.html#state">state</a>() == QSocket::Closing ) {
279 // We have a delayed close.
280<a name="x800"></a> connect( socket, SIGNAL(<a href="qsocket.html#delayedCloseFinished">delayedCloseFinished</a>()),
281 SLOT(socketClosed()) );
282 } else {
283 // The socket is closed.
284 socketClosed();
285 }
286 }
287
288 void sendToServer()
289 {
290 // write to the server
291 <a href="qtextstream.html">QTextStream</a> os(socket);
292<a name="x794"></a> os &lt;&lt; inputText-&gt;<a href="qlineedit.html#text">text</a>() &lt;&lt; "\n";
293<a name="x793"></a> inputText-&gt;<a href="qlineedit.html#setText">setText</a>( "" );
294 }
295
296 void socketReadyRead()
297 {
298 // read from the server
299<a name="x795"></a> while ( socket-&gt;<a href="qsocket.html#canReadLine">canReadLine</a>() ) {
300<a name="x802"></a> infoText-&gt;<a href="qtextedit.html#append">append</a>( socket-&gt;<a href="qsocket.html#readLine">readLine</a>() );
301 }
302 }
303
304 void socketConnected()
305 {
306 infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("Connected to server\n") );
307 }
308
309 void socketConnectionClosed()
310 {
311 infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("Connection closed by the server\n") );
312 }
313
314 void socketClosed()
315 {
316 infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("Connection closed\n") );
317 }
318
319 void socketError( int e )
320 {
321 infoText-&gt;<a href="qtextedit.html#append">append</a>( tr("Error number %1 occurred\n").arg(e) );
322 }
323
324private:
325 <a href="qsocket.html">QSocket</a> *socket;
326 <a href="qtextview.html">QTextView</a> *infoText;
327 <a href="qlineedit.html">QLineEdit</a> *inputText;
328};
329
330
331int main( int argc, char** argv )
332{
333 <a href="qapplication.html">QApplication</a> app( argc, argv );
334 Client client( argc&lt;2 ? "localhost" : argv[1], 4242 );
335 app.<a href="qapplication.html#setMainWidget">setMainWidget</a>( &amp;client );
336 client.<a href="qwidget.html#show">show</a>();
337 return app.<a href="qapplication.html#exec">exec</a>();
338}
339
340#include "client.moc"
341</pre>
342
343<p>See also <a href="network-examples.html">Network Examples</a>.
344
345<!-- eof -->
346<p><address><hr><div align=center>
347<table width=100% cellspacing=0 border=0><tr>
348<td>Copyright &copy; 2007
349<a href="troll.html">Trolltech</a><td align=center><a href="trademarks.html">Trademarks</a>
350<td align=right><div align=right>Qt 3.3.8</div>
351</table></div></address></body>
352</html>
Note: See TracBrowser for help on using the repository browser.