KDELibs4Support

k3serversocket.h
1 /* -*- C++ -*-
2  * Copyright (C) 2003,2005 Thiago Macieira <[email protected]>
3  *
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining
6  * a copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sublicense, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */
24 
25 #ifndef KSERVERSOCKET_H
26 #define KSERVERSOCKET_H
27 
28 #include <QObject>
29 #include "k3socketbase.h"
30 #include "k3streamsocket.h"
31 
32 namespace KNetwork
33 {
34 
35 class KStreamSocket;
36 class KResolver;
37 class KResolverResults;
38 
39 class KServerSocketPrivate;
40 /**
41  * @class KServerSocket k3serversocket.h k3serversocket.h
42  * @brief A server socket for accepting connections.
43  *
44  * This class provides functionality for creating a socket to
45  * listen for incoming connections and subsequently accept them.
46  *
47  * To use this class, you must first set the parameters for the listening
48  * socket's address, then place it in listening mode.
49  *
50  * A typical example would look like:
51  * \code
52  * QString service = "http";
53  * KServerSocket *ss = new KServerSocket(service);
54  * connect(ss, SIGNAL(readyAccept()), this, SLOT(slotReadyAccept()));
55  * connect(ss, SIGNAL(gotError(int)), this, SLOT(slotSocketError(int)));
56  * ss->listen();
57  * \endcode
58  *
59  * In this case, this class will place the socket into listening mode on the
60  * service pointed to by @p service and will emit the readyAccept() signal
61  * when a connection is ready for accepting. The called slot is responsible for
62  * calling accept().
63  *
64  * The location of the services file (where @p service is looked up)
65  * is defined by _PATH_SERVICES in /usr/include/netdb.h. This is
66  * usually set to /etc/services.
67  * See RFC 1700 for more information on services.
68  * You can specify @p service as a port number directly, rather than as a service
69  * name. This is discouraged as it prevents the end user from easily modifying
70  * the port number.
71  *
72  * For another example of usage, this below code attempts to make a connection on any port within a range:
73  * \code
74  * KServerSocket *ss = new KServerSocket();
75  * ss->setFamily(KResolver::InetFamily);
76  * bool found = false;
77  * for( unsigned int port = firstport; port <= lastport; ++port) {
78  * ss->setAddress( QString::number( port ) );
79  * bool success = ss->listen();
80  * if( found = ( success && ss->error() ==
81  * KSocketBase::NoError ) )
82  * break;
83  * ss->close();
84  * }
85  * if( !found ) {
86  * // Couldn't connect to any port.
87  * } else {
88  * connect(ss, SIGNAL(readyAccept()), this, SLOT(slotReadyAccept()));
89  * connect(ss, SIGNAL(gotError(int)), this, SLOT(slotSocketError(int)));
90  * ss->listen();
91  * }
92  * \endcode
93  *
94  * The called slot slotReadyAccept() is responsible for calling
95  * accept().
96  *
97  * It is important to note that accept() can return either an
98  * object of type KNetwork::KStreamSocket or
99  * KNetwork::KBufferedSocket (default). If you want to accept a
100  * non-buffered socket, you must first call setAcceptBuffered.
101  *
102  * @warning If you use KServerSocket in an auxiliary (non-GUI) thread,
103  * you need to accept only KNetwork::KStreamSocket objects.
104  *
105  * @see KNetwork::KStreamSocket, KNetwork::KBufferedSocket
106  * @author Thiago Macieira <[email protected]>
107  * @deprecated Use KSocketFactory or KLocalSocket instead
108  */
109 class KDELIBS4SUPPORT_DEPRECATED_EXPORT KServerSocket: public QObject, public KPassiveSocketBase
110 {
111  Q_OBJECT
112 public:
113  /**
114  * Default constructor.
115  *
116  * If the binding address isn't changed by setAddress, this socket will
117  * bind to all interfaces on this node and the port will be selected by the
118  * operating system.
119  *
120  * @param parent the parent QObject object
121  */
122  KServerSocket(QObject *parent = nullptr);
123 
124  /**
125  * Construct this object specifying the service to listen on.
126  *
127  * If the binding address isn't changed by setAddress, this socket will
128  * bind to all interfaces and will listen on the port specified by
129  * @p service. This is either a service name (e.g. 'www') or a port
130  * number (e.g. '80').
131  *
132  * The location of the services file (where @p service is looked up)
133  * is defined by _PATH_SERVICES in /usr/include/netdb.h. This is
134  * usually set to /etc/services.
135  * See RFC 1700 for more information on services.
136  *
137  * @param service the service name to listen on
138  * @param parent the parent QObject object
139  */
140  KDELIBS4SUPPORT_DEPRECATED explicit KServerSocket(const QString &service, QObject *parent = nullptr);
141 
142  /**
143  * Construct this object specifying the node and service names to listen on.
144  *
145  * If the binding address isn't changed by setAddress, this socket will
146  * bind to the interface specified by @p node and the port specified by
147  * @p service. This is either a service name (e.g. 'www') or a port
148  * number (e.g. '80').
149  *
150  * The location of the services file (where @p service is looked up)
151  * is defined by _PATH_SERVICES in /usr/include/netdb.h. This is
152  * usually set to /etc/services.
153  * See RFC 1700 for more information on services.
154  *
155  * @param node the node to bind to
156  * @param service the service port to listen on
157  * @param parent the parent QObject object
158  */
159  KServerSocket(const QString &node, const QString &service,
160  QObject *parent = nullptr);
161 
162  /**
163  * Destructor. This will close the socket, if open.
164  *
165  * Note, however, that accepted sockets do not get closed when this
166  * object closes.
167  */
168  ~KServerSocket() override;
169 
170 protected:
171  /**
172  * Sets the socket options. Reimplemented from KSocketBase.
173  */
174  bool setSocketOptions(int opts) override;
175 
176 public:
177  /**
178  * Returns the internal KResolver object used for
179  * looking up the host name and service.
180  *
181  * This can be used to set extra options to the
182  * lookup process other than the default values, as well
183  * as obtaining the error codes in case of lookup failure.
184  */
185  KResolver &resolver() const;
186 
187  /**
188  * Returns the internal list of resolved results for the binding address.
189  */
190  const KResolverResults &resolverResults() const;
191 
192  /**
193  * Enables or disables name resolution. If this flag is set to true,
194  * the bind() operation will trigger name lookup
195  * operations (i.e., converting a hostname into its binary form).
196  * If the flag is set to false, those operations will instead
197  * try to convert a string representation of an address without
198  * attempting name resolution.
199  *
200  * This is useful, for instance, when IP addresses are in
201  * their string representation (such as "1.2.3.4") or come
202  * from other sources like KSocketAddress.
203  *
204  * @param enable whether to enable
205  */
206  void setResolutionEnabled(bool enable);
207 
208  /**
209  * Sets the allowed families for the resolutions.
210  *
211  * @param families the families that we want/accept
212  * @see KResolver::SocketFamilies for possible values
213  */
214  void setFamily(int families);
215 
216  /**
217  * Sets the address on which we will listen. The port to listen on is given by
218  * @p service, and we will bind to all interfaces. To let the operating system choose a
219  * port, set the service to "0". @p service can either be a service name
220  * (e.g. 'www') or a port number (e.g. '80').
221  *
222  * The location of the services file (where @p service is looked up)
223  * is defined by _PATH_SERVICES in /usr/include/netdb.h. This is
224  * usually set to /etc/services.
225  * See RFC 1700 for more information on services.
226  *
227  * @param service the service name to listen on
228  */
229  void setAddress(const QString &service);
230 
231  /**
232  * @overload
233  * Sets the address on which we will listen. This will cause the socket to listen
234  * only on the interface given by @p node and on the port given by @p service.
235  * @p service can either be a service name (e.g. 'www') or a port number
236  * (e.g. '80').
237  *
238  * The location of the services file (where @p service is looked up)
239  * is defined by _PATH_SERVICES in /usr/include/netdb.h. This is
240  * usually set to /etc/services.
241  * See RFC 1700 for more information on services.
242  *
243  * @param node the node to bind to
244  * @param service the service port to listen on
245  */
246  void setAddress(const QString &node, const QString &service);
247 
248  /**
249  * Sets the timeout for accepting. When you call accept(),
250  * it will wait at most @p msecs milliseconds or return with an error
251  * (returning a NULL object).
252  *
253  * @param msecs the time in milliseconds to wait, 0 to wait forever
254  */
255  void setTimeout(int msecs);
256 
257  /**
258  * Starts the lookup for peer and local hostnames as
259  * well as their services.
260  *
261  * If the blocking mode for this object is on, this function will
262  * wait for the lookup results to be available (by calling the
263  * KResolver::wait() method on the resolver objects).
264  *
265  * When the lookup is done, the signal hostFound() will be
266  * emitted (only once, even if we're doing a double lookup).
267  * If the lookup failed (for any of the two lookups) the
268  * gotError() signal will be emitted with the appropriate
269  * error condition (see KSocketBase::SocketError).
270  *
271  * This function returns true on success and false on error. Note that
272  * this is not the lookup result!
273  */
274  virtual bool lookup();
275 
276  /**
277  * Binds this socket to the given nodename and service,
278  * or use the default ones if none are given.
279  *
280  * Upon successful binding, the bound() signal will be
281  * emitted. If an error is found, the gotError()
282  * signal will be emitted.
283  *
284  * This function returns true on success.
285  *
286  * @param node the nodename
287  * @param service the service
288  */
289  virtual bool bind(const QString &node, const QString &service);
290 
291  /**
292  * Binds the socket to the given service name.
293  * @overload
294  *
295  * @param service the service
296  */
297  virtual bool bind(const QString &service);
298 
299  /**
300  * Binds the socket to the addresses previously set with setAddress().
301  * @overload
302  *
303  */
304  virtual bool bind();
305 
306  /**
307  * Connect this socket to this specific address. Reimplemented from KSocketBase.
308  *
309  * Unlike bind(const QString&, const QString&) above, this function
310  * really does bind the socket. No lookup is performed. The bound() signal
311  * will be emitted.
312  */
313  bool bind(const KResolverEntry &address) override;
314 
315  /**
316  * Puts this socket into listening mode. Reimplemented from KPassiveSocketBase.
317  *
318  * Placing a socket into listening mode means it will be able to receive incoming
319  * connections through the accept() method.
320  *
321  * If you do not call this method but call accept() directly, the socket will
322  * be placed into listening mode automatically.
323  *
324  * @param backlog the number of connection the system is to
325  * queue without accept() being called
326  * @returns true if the socket is now in listening mode.
327  */
328  bool listen(int backlog = 5) override; // 5 is arbitrary
329 
330  /**
331  * Closes this socket.
332  */
333  void close() override;
334 
335  /**
336  * Toggles whether the accepted socket will be buffered or not.
337  * That is, the accept() function will always return a KStreamSocket
338  * object or descended from it. If buffering is enabled, the class
339  * to be returned will be KBufferedSocket.
340  *
341  * By default, this flag is set to true.
342  *
343  * @param enable whether to set the accepted socket to
344  * buffered mode
345  */
346  void setAcceptBuffered(bool enable);
347 
348  /**
349  * Accepts one incoming connection and return the associated, open
350  * socket.
351  *
352  * If this function cannot accept a new connection, it will return NULL.
353  * The specific object class returned by this function may vary according
354  * to the implementation: derived classes may return specialized objects
355  * descended from KStreamSocket.
356  *
357  * @sa KBufferedSocket
358  * @sa setAcceptBuffered
359  */
360  KStreamSocket *accept() override;
361 
362  /**
363  * Returns this socket's local address.
364  */
365  KSocketAddress localAddress() const override;
366 
367  /**
368  * Returns this socket's externally-visible address if know.
369  */
370  KSocketAddress externalAddress() const override;
371 
372 private Q_SLOTS:
373  void lookupFinishedSlot();
374 
375 Q_SIGNALS:
376  /**
377  * This signal is emitted when this object finds an error.
378  * The @p code parameter contains the error code that can
379  * also be found by calling error().
380  */
381  void gotError(int code);
382 
383  /**
384  * This signal is emitted when the lookup is successfully completed.
385  */
386  void hostFound();
387 
388  /**
389  * This signal is emitted when the socket successfully binds
390  * to an address.
391  *
392  * @param local the local address we bound to
393  */
394  void bound(const KNetwork::KResolverEntry &local);
395 
396  /**
397  * This signal is emitted when the socket completes the
398  * closing/shut down process.
399  */
400  void closed();
401 
402  /**
403  * This signal is emitted whenever the socket is ready for
404  * accepting -- i.e., there is at least one connection waiting to
405  * be accepted.
406  */
407  void readyAccept();
408 
409 protected:
410  /**
411  * Convenience function to set this object's error code to match
412  * that of the socket device.
413  */
414  void copyError();
415 
416 private:
417  bool doBind();
418  bool doListen();
419 
420 private:
421  KServerSocket(const KServerSocket &);
422  KServerSocket &operator=(const KServerSocket &);
423 
424  KServerSocketPrivate *const d;
425 };
426 
427 } // namespace KNetwork
428 
429 #endif
Simple stream socket.
A server socket for accepting connections.
One resolution entry.
Definition: k3resolver.h:72
Name and service resolution class.
Definition: k3resolver.h:312
A generic socket address.
Name and service resolution results.
Definition: k3resolver.h:212
A namespace to store all networking-related (socket) classes.
Abstract base class for passive sockets.
Definition: k3socketbase.h:773
This file is part of the KDE documentation.
Documentation copyright © 1996-2021 The KDE developers.
Generated on Mon Oct 18 2021 23:00:51 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.