KDEGames

kmessageserver.h
1 /*
2  This file is part of the KDE games library
3  SPDX-FileCopyrightText: 2001 Burkhard Lehner <[email protected]>
4 
5  SPDX-License-Identifier: LGPL-2.0-only
6 */
7 
8 #ifndef __KMESSAGESERVER_H__
9 #define __KMESSAGESERVER_H__
10 
11 // own
12 #include "libkdegamesprivate_export.h"
13 // Qt
14 #include <QObject>
15 #include <QString>
16 // Std
17 #include <memory>
18 
19 class KMessageIO;
20 class KMessageServerPrivate;
21 
22 /**
23  \class KMessageServer kmessageserver.h <KGame/KMessageServer>
24 
25  @short A server for message sending and broadcasting, using TCP/IP connections.
26 
27  An object of this class listens for incoming connections via TCP/IP sockets and
28  creates KMessageSocket objects for every established connection. It receives
29  messages from the "clients", analyzes them and processes an appropriate
30  reaction.
31 
32  You can also use other KMessageIO objects with KMessageServer, not only
33  TCP/IP socket based ones. Use addClient to connect via an object of any
34  KMessageIO subclass. (For clients within the same process, you can e.g. use
35  KMessageDirect.) This object already has to be connected.
36 
37  The messages are always packages of an arbitrary length. The format of the messages
38  is given below. All the data is stored and received with QDataStream, to be
39  platform independent.
40 
41  Setting up a KMessageServer can be done like this:
42 
43  \code
44  KMessageServer *server = new KMessageServer ();
45  server->initNetwork (TCP/IP-Portnumber);
46  \endcode
47 
48  Usually that is everything you will do. There are a lot of public methods to
49  administrate the object (maximum number of clients, finding clients, removing
50  clients, setting the admin client, ...), but this functionality can also
51  be done by messages from the clients. So you can administrate the object completely
52  on remote.
53 
54  If you want to extend the Server for your own needs (e.g. additional message types),
55  you can either create a subclass and overwrite the method processOneMessage.
56  (But don't forget to call the method of the superclass!) Or you can connect to
57  the signal messageReceived, and analyze the messages there.
58 
59  Every client has a unique ID, so that messages can be sent to another dedicated
60  client or a list of clients.
61 
62  One of the clients (the admin) has a special administration right. Some of the
63  administration messages can only be used with him. The admin can give the admin
64  status to another client. You can send a message to the admin by using clientID 0.
65  This is always interpreted as the admin client, of its real clientID.
66 
67  Here is a list of the messages the KMessageServer understands:
68  &lt;&lt; means, the value is inserted into the QByteArray using QDataStream. The
69  messageIDs (REQ_BROADCAST, ...) are of type quint32.
70 
71  - QByteArray << static_cast&lt;quint32>( REQ_BROADCAST ) << raw_data
72 
73  When the server receives this message, it sends the following message to
74  ALL connected clients (a broadcast), where the raw_data is left unchanged:
75  QByteArray << static_cast &lt;quint32>( MSG_BROADCAST ) << clientID << raw_data
76  quint32 clientID; // the ID of the client that sent the broadcast request
77 
78  - QByteArray << static_cast&lt;quint32>( REQ_FORWARD ) << client_list << raw_data
79  QValueList &lt;quint32> client_list; // list of receivers
80 
81  When the server receives this message, it sends the following message to
82  the clients in client_list:
83  QByteArray << static_cast&lt;quint32>( MSG_FORWARD ) << senderID << client_list << raw_data
84  quint32 senderID; // the sender of the forward request
85  QValueList &lt;quint32> client_list; // a copy of the receiver list
86 
87  Note: Every client receives the message as many times as he is in the client_list.
88  Note: Since the client_list is sent to all the clients, every client can see who else
89  got the message. If you want to prevent this, send a single REQ_FORWARD
90  message for every receiver.
91 
92  - QByteArray << static_cast&lt;quint32>( REQ_CLIENT_ID )
93 
94  When the server receives this message, it sends the following message to
95  the asking client:
96  QByteArray << static_cast&lt;quint32>( ANS_CLIENT_ID ) << clientID
97  quint32 clientID; // The ID of the client who asked for it
98 
99  Note: This answer is also automatically sent to a new connected client, so that he
100  can store his ID. The ID of a client doesn't change during his lifetime, and is
101  unique for this KMessageServer.
102 
103  - QByteArray << static_cast&lt;quint32>( REQ_ADMIN_ID )
104 
105  When the server receives this message, it sends the following message to
106  the asking client:
107  QByteArray << ANS_ADMIN_ID << adminID
108  quint32 adminID; // The ID of the admin
109 
110  Note: This answer is also automatically sent to a new connected client, so that he
111  can see if he is the admin or not. It will also be sent to all connected clients
112  when a new admin is set (see REQ_ADMIN_CHANGE).
113 
114  - QByteArray << static_cast&lt;quint32>( REQ_ADMIN_CHANGE ) << new_admin
115  quint32 new_admin; // the ID of the new admin, or 0 for no admin
116 
117  When the server receives this message, it sets the admin to the new ID. If no client
118  with that ID exists, nothing happens. With new_admin == 0 no client is a admin.
119  ONLY THE ADMIN ITSELF CAN USE THIS MESSAGE!
120 
121  Note: The server sends a ANS_ADMIN_ID message to every connected client.
122 
123  - QByteArray << static_cast&lt;quint32>( REQ_REMOVE_CLIENT ) << client_list
124  QValueList &lt;quint32> client_list; // The list of clients to be removed
125 
126  When the server receives this message, it removes the clients with the ids stored in
127  client_list, disconnecting the connection to them.
128  ONLY THE ADMIN CAN USE THIS MESSAGE!
129 
130  Note: If one of the clients is the admin himself, he will also be deleted.
131  Another client (if any left) will become the new admin.
132 
133  - QByteArray << static_cast&lt;quint32>( REQ_MAX_NUM_CLIENTS ) << maximum_clients
134  qint32 maximum_clients; // The maximum of clients connected, or infinite if -1
135 
136  When the server receives this message, it limits the number of clients to the number given,
137  or sets it unlimited for maximum_clients == -1.
138  ONLY THE ADMIN CAN USE THIS MESSAGE!
139 
140  Note: If there are already more clients, they are not affected. It only prevents new Clients
141  to be added. To assure this limit, remove clients afterwards (REQ_REMOVE_CLIENT)
142 
143  - QByteArray << static_cast&lt;quint32>( REQ_CLIENT_LIST )
144 
145  When the server receives this message, it answers by sending a list of IDs of all the clients
146  that are connected at the moment. So it sends the following message to the asking client:
147  QByteArray << static_cast&lt;quint32>( ANS_CLIENT_LIST ) << clientList
148  QValueList &lt;quint32> clientList; // The IDs of the connected clients
149 
150  Note: This message is also sent to every new connected client, so that he knows the other
151  clients.
152 
153  There are two more messages that are sent from the server to the every client automatically
154  when a new client connects or a connection to a client is lost:
155 
156  QByteArray << static_cast&lt;quint32>( EVNT_CLIENT_CONNECTED ) << clientID;
157  quint32 clientID; // the ID of the new connected client
158 
159  QByteArray << static_cast&lt;quint32>( EVNT_CLIENT_DISCONNECTED ) << clientID;
160  quint32 clientID; // the ID of the client that lost the connection
161  quint8 broken; // 1 if the network connection was closed, 0 if it was disconnected
162  // on purpose
163 
164 
165  @author Andreas Beckermann <[email protected]>, Burkhard Lehner <[email protected]>
166 */
167 class KDEGAMESPRIVATE_EXPORT KMessageServer : public QObject
168 {
169  Q_OBJECT
170 
171 public:
172  /**
173  MessageIDs for messages from a client to the message server.
174  */
175  enum {
176  REQ_BROADCAST = 1,
177  REQ_FORWARD,
178  REQ_CLIENT_ID,
179  REQ_ADMIN_ID,
180  REQ_ADMIN_CHANGE,
181  REQ_REMOVE_CLIENT,
182  REQ_MAX_NUM_CLIENTS,
183  REQ_CLIENT_LIST,
184  REQ_MAX_REQ = 0xffff };
185 
186  /**
187  * MessageIDs for messages from the message server to a client.
188  **/
189  enum {
190  MSG_BROADCAST = 101,
191  MSG_FORWARD,
192  ANS_CLIENT_ID,
193  ANS_ADMIN_ID,
194  ANS_CLIENT_LIST,
195  EVNT_CLIENT_CONNECTED,
196  EVNT_CLIENT_DISCONNECTED,
197  EVNT_MAX_EVNT = 0xffff
198  };
199 
200  /**
201  * Create a KGameNetwork object
202  **/
203  explicit KMessageServer(quint16 cookie = 42, QObject* parent = nullptr);
204 
205  ~KMessageServer() override;
206 
207  /**
208  * Gives debug output of the game status
209  **/
210  virtual void Debug();
211 
212 //---------------------------------- TCP/IP server stuff
213 
214  /**
215  * Starts the Communication server to listen for incoming TCP/IP connections.
216  *
217  * @param port The port on which the service is offered, or 0 to let the
218  * system pick a free port
219  * @return true if it worked
220  */
221  bool initNetwork (quint16 port = 0);
222 
223  /**
224  * Returns the TCP/IP port number we are listening to for incoming connections.
225  * (This has to be known by other clients so that they can connect to us. It's
226  * especially necessary if you used 0 as port number in initNetwork().
227  * @return the port number
228  **/
229  quint16 serverPort () const;
230 
231  /**
232  * Stops listening for connections. The already running connections are
233  * not affected.
234  * To listen for connections again call initNetwork again.
235  **/
236  void stopNetwork();
237 
238  /**
239  * Are we still offer offering server connections?
240  * @return true, if we are still listening to connections requests
241  **/
242  bool isOfferingConnections() const;
243 
244 //---------------------------------- adding / removing clients
245 
246 public Q_SLOTS:
247  /**
248  * Adds a new @ref KMessageIO object to the communication server. This "client"
249  * gets a unique ID.
250  *
251  * This slot method is automatically called for any incoming TCP/IP
252  * connection. You can use it to add other types of connections, e.g.
253  * local connections (KMessageDirect) to the server manually.
254  *
255  * NOTE: The @ref KMessageIO object gets owned by the KMessageServer,
256  * so don't delete or manipulate it afterwards. It is automatically deleted
257  * when the connection is broken or the communication server is deleted.
258  * So, add a @ref KMessageIO object to just ONE KMessageServer.
259  **/
260  void addClient (KMessageIO *);
261 
262  /**
263  * Removes the KMessageIO object from the client list and deletes it.
264  * This destroys the connection, if it already was up.
265  * Does NOT emit connectionLost.
266  * Sends an info message to the other clients, that contains the ID of
267  * the removed client and the value of the parameter broken.
268  *
269  * @param io the object to delete and to remove from the client list
270  * @param broken true if the client has lost connection
271  * Mostly used internally. You will probably not need this.
272  **/
273  void removeClient (KMessageIO *io, bool broken);
274 
275  /**
276  Deletes all connections to the clients.
277  */
278  void deleteClients();
279 
280 private Q_SLOTS:
281  /**
282  * Removes the sender object of the signal that called this slot. It is
283  * automatically connected to @ref KMessageIO::connectionBroken.
284  * Emits @ref connectionLost (KMessageIO*), and deletes the @ref KMessageIO object.
285  * Don't call it directly!
286  **/
287  void removeBrokenClient ();
288 
289 public:
290  /**
291  * sets the maximum number of clients which can connect.
292  * If this number is reached, no more clients can be added.
293  * Setting this number to -1 means unlimited number of clients.
294  *
295  * NOTE: Existing connections are not affected.
296  * So, clientCount > maxClients is possible, if there were already
297  * more clients than allowed before reducing this value.
298  *
299  * @param maxnumber the number of clients
300  **/
301  void setMaxClients(int maxnumber);
302 
303  /**
304  * returns the maximum number of clients
305  *
306  * @return the number of clients
307  **/
308  int maxClients() const;
309 
310  /**
311  * returns the current number of connected clients.
312  *
313  * @return the number of clients
314  **/
315  int clientCount() const;
316 
317  /**
318  * returns a list of the unique IDs of all clients.
319  **/
320  QList <quint32> clientIDs() const;
321 
322  /**
323  * Find the @ref KMessageIO object to the given client number.
324  * @param no the client number to look for, or 0 to look for the admin
325  * @return address of the client, or 0 if no client with that number exists
326  **/
327  KMessageIO *findClient (quint32 no) const;
328 
329  /**
330  * Returns the clientID of the admin, if there is a admin, 0 otherwise.
331  *
332  * NOTE: Most often you don't need to know that id, since you can
333  * use clientID 0 to specify the admin.
334  **/
335  quint32 adminID() const;
336 
337  /**
338  * Sets the admin to a new client with the given ID.
339  * The old admin (if existed) and the new admin will get the ANS_ADMIN message.
340  * If you use 0 as new adminID, no client will be admin.
341  **/
342  void setAdmin (quint32 adminID);
343 
344 
345 //------------------------------ ID stuff
346 
347  /*
348  * The unique ID of this game
349  *
350  * @return int id
351  **/
352 // int gameId() const;
353 
354  /*
355  * Application cookie. this identifies the game application. It
356  * help to distinguish between e.g. KPoker and KWin4
357  *
358  * @return the application cookie
359  **/
360 // int cookie() const;
361 
362 //------------------------------ Message stuff
363 
364 public:
365  /**
366  * Sends a message to all connected clients.
367  * The message is NOT translated in any way. This method calls
368  * @ref KMessageIO::send for every client added.
369  **/
370  virtual void broadcastMessage (const QByteArray &msg);
371 
372  /**
373  * Sends a message to a single client with the given ID.
374  * The message is NOT translated in any way.
375  * If no client with the given id exists, nothing is done.
376  * This is just a convenience method. You could also call
377  * @ref findClient (id)->send(msg) manually, but this method checks for
378  * errors.
379  **/
380  virtual void sendMessage (quint32 id, const QByteArray &msg);
381 
382  /**
383  * Sends a message to a list of clients. Their ID is given in ids. If
384  * a client id is given more than once in the list, the message is also
385  * sent several times to that client.
386  * This is just a convenience method. You could also iterate over the
387  * list of IDs.
388  **/
389  virtual void sendMessage (const QList <quint32> &ids, const QByteArray &msg);
390 
391 protected Q_SLOTS:
392  /**
393  * This slot receives all the messages from the @ref KMessageIO::received signals.
394  * It stores the messages in a queue. The messages are later taken out of the queue
395  * by @ref getReceivedMessage.
396  *
397  * NOTE: It is important that this slot may only be called from the signal
398  * @ref KMessageIO::received, since the sender() object is used to find out
399  * the client that sent the message!
400  **/
401  virtual void getReceivedMessage (const QByteArray &msg);
402 
403  /**
404  * This slot is called whenever there are elements in the message queue. This queue
405  * is filled by @ref getReceivedMessage.
406  * This slot takes one message out of the queue and analyzes processes it,
407  * if it recognizes it. (See message types in the description of the class.)
408  * After that, the signal @ref messageReceived is emitted. Connect to that signal if
409  * you want to process other types of messages.
410  **/
411  virtual void processOneMessage ();
412 
413 //---------------------------- Signals
414 
415 Q_SIGNALS:
416  /**
417  * A new client connected to the game
418  * @param client the client object that connected
419  **/
420  void clientConnected (KMessageIO *client);
421 
422  /**
423  * A network connection got broken. Note that the client will automatically get deleted
424  * after this signal is emitted. The signal is not emitted when the client was removed
425  * regularly.
426  *
427  * @param client the client which left the game
428  **/
429  void connectionLost (KMessageIO *client);
430 
431  /**
432  * This signal is always emitted when a message from a client is received.
433  *
434  * You can use this signal to extend the communication server without subclassing.
435  * Just connect to this signal and analyze the message, if unknown is true.
436  * If you recognize a message and process it, set unknown to false, otherwise
437  * a warning message is printed.
438  *
439  * @param data the message data
440  * @param clientID the ID of the KMessageIO object that received the message
441  * @param unknown true, if the message type is not known by the KMessageServer
442  **/
443  void messageReceived (const QByteArray &data, quint32 clientID, bool &unknown);
444 
445 protected:
446  /**
447  * @return A unique number which can be used as the id of a @ref KMessageIO. It is
448  * incremented after every call so if you need the id twice you have to save
449  * it anywhere. It's currently used to initialize newly connected clients only.
450  **/
451  quint32 uniqueClientNumber() const;
452 
453 private:
454  std::unique_ptr<KMessageServerPrivate> const d;
455 };
456 
457 
458 #endif
This abstract base class represents one end of a message connections between two clients.
Definition: kmessageio.h:51
A server for message sending and broadcasting, using TCP/IP connections.
This file is part of the KDE documentation.
Documentation copyright © 1996-2021 The KDE developers.
Generated on Tue Dec 7 2021 22:34:15 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.