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 // Std
16 #include <memory>
17 
18 class KMessageIO;
19 class KMessageServerPrivate;
20 
21 /**
22  \class KMessageServer kmessageserver.h <KGame/KMessageServer>
23 
24  @short A server for message sending and broadcasting, using TCP/IP connections.
25 
26  An object of this class listens for incoming connections via TCP/IP sockets and
27  creates KMessageSocket objects for every established connection. It receives
28  messages from the "clients", analyzes them and processes an appropriate
29  reaction.
30 
31  You can also use other KMessageIO objects with KMessageServer, not only
32  TCP/IP socket based ones. Use addClient to connect via an object of any
33  KMessageIO subclass. (For clients within the same process, you can e.g. use
34  KMessageDirect.) This object already has to be connected.
35 
36  The messages are always packages of an arbitrary length. The format of the messages
37  is given below. All the data is stored and received with QDataStream, to be
38  platform independent.
39 
40  Setting up a KMessageServer can be done like this:
41 
42  \code
43  KMessageServer *server = new KMessageServer ();
44  server->initNetwork (TCP/IP-Portnumber);
45  \endcode
46 
47  Usually that is everything you will do. There are a lot of public methods to
48  administrate the object (maximum number of clients, finding clients, removing
49  clients, setting the admin client, ...), but this functionality can also
50  be done by messages from the clients. So you can administrate the object completely
51  on remote.
52 
53  If you want to extend the Server for your own needs (e.g. additional message types),
54  you can either create a subclass and overwrite the method processOneMessage.
55  (But don't forget to call the method of the superclass!) Or you can connect to
56  the signal messageReceived, and analyze the messages there.
57 
58  Every client has a unique ID, so that messages can be sent to another dedicated
59  client or a list of clients.
60 
61  One of the clients (the admin) has a special administration right. Some of the
62  administration messages can only be used with him. The admin can give the admin
63  status to another client. You can send a message to the admin by using clientID 0.
64  This is always interpreted as the admin client, of its real clientID.
65 
66  Here is a list of the messages the KMessageServer understands:
67  &lt;&lt; means, the value is inserted into the QByteArray using QDataStream. The
68  messageIDs (REQ_BROADCAST, ...) are of type quint32.
69 
70  - QByteArray << static_cast&lt;quint32>( REQ_BROADCAST ) << raw_data
71 
72  When the server receives this message, it sends the following message to
73  ALL connected clients (a broadcast), where the raw_data is left unchanged:
74  QByteArray << static_cast &lt;quint32>( MSG_BROADCAST ) << clientID << raw_data
75  quint32 clientID; // the ID of the client that sent the broadcast request
76 
77  - QByteArray << static_cast&lt;quint32>( REQ_FORWARD ) << client_list << raw_data
78  QValueList &lt;quint32> client_list; // list of receivers
79 
80  When the server receives this message, it sends the following message to
81  the clients in client_list:
82  QByteArray << static_cast&lt;quint32>( MSG_FORWARD ) << senderID << client_list << raw_data
83  quint32 senderID; // the sender of the forward request
84  QValueList &lt;quint32> client_list; // a copy of the receiver list
85 
86  Note: Every client receives the message as many times as he is in the client_list.
87  Note: Since the client_list is sent to all the clients, every client can see who else
88  got the message. If you want to prevent this, send a single REQ_FORWARD
89  message for every receiver.
90 
91  - QByteArray << static_cast&lt;quint32>( REQ_CLIENT_ID )
92 
93  When the server receives this message, it sends the following message to
94  the asking client:
95  QByteArray << static_cast&lt;quint32>( ANS_CLIENT_ID ) << clientID
96  quint32 clientID; // The ID of the client who asked for it
97 
98  Note: This answer is also automatically sent to a new connected client, so that he
99  can store his ID. The ID of a client doesn't change during his lifetime, and is
100  unique for this KMessageServer.
101 
102  - QByteArray << static_cast&lt;quint32>( REQ_ADMIN_ID )
103 
104  When the server receives this message, it sends the following message to
105  the asking client:
106  QByteArray << ANS_ADMIN_ID << adminID
107  quint32 adminID; // The ID of the admin
108 
109  Note: This answer is also automatically sent to a new connected client, so that he
110  can see if he is the admin or not. It will also be sent to all connected clients
111  when a new admin is set (see REQ_ADMIN_CHANGE).
112 
113  - QByteArray << static_cast&lt;quint32>( REQ_ADMIN_CHANGE ) << new_admin
114  quint32 new_admin; // the ID of the new admin, or 0 for no admin
115 
116  When the server receives this message, it sets the admin to the new ID. If no client
117  with that ID exists, nothing happens. With new_admin == 0 no client is a admin.
118  ONLY THE ADMIN ITSELF CAN USE THIS MESSAGE!
119 
120  Note: The server sends a ANS_ADMIN_ID message to every connected client.
121 
122  - QByteArray << static_cast&lt;quint32>( REQ_REMOVE_CLIENT ) << client_list
123  QValueList &lt;quint32> client_list; // The list of clients to be removed
124 
125  When the server receives this message, it removes the clients with the ids stored in
126  client_list, disconnecting the connection to them.
127  ONLY THE ADMIN CAN USE THIS MESSAGE!
128 
129  Note: If one of the clients is the admin himself, he will also be deleted.
130  Another client (if any left) will become the new admin.
131 
132  - QByteArray << static_cast&lt;quint32>( REQ_MAX_NUM_CLIENTS ) << maximum_clients
133  qint32 maximum_clients; // The maximum of clients connected, or infinite if -1
134 
135  When the server receives this message, it limits the number of clients to the number given,
136  or sets it unlimited for maximum_clients == -1.
137  ONLY THE ADMIN CAN USE THIS MESSAGE!
138 
139  Note: If there are already more clients, they are not affected. It only prevents new Clients
140  to be added. To assure this limit, remove clients afterwards (REQ_REMOVE_CLIENT)
141 
142  - QByteArray << static_cast&lt;quint32>( REQ_CLIENT_LIST )
143 
144  When the server receives this message, it answers by sending a list of IDs of all the clients
145  that are connected at the moment. So it sends the following message to the asking client:
146  QByteArray << static_cast&lt;quint32>( ANS_CLIENT_LIST ) << clientList
147  QValueList &lt;quint32> clientList; // The IDs of the connected clients
148 
149  Note: This message is also sent to every new connected client, so that he knows the other
150  clients.
151 
152  There are two more messages that are sent from the server to the every client automatically
153  when a new client connects or a connection to a client is lost:
154 
155  QByteArray << static_cast&lt;quint32>( EVNT_CLIENT_CONNECTED ) << clientID;
156  quint32 clientID; // the ID of the new connected client
157 
158  QByteArray << static_cast&lt;quint32>( EVNT_CLIENT_DISCONNECTED ) << clientID;
159  quint32 clientID; // the ID of the client that lost the connection
160  quint8 broken; // 1 if the network connection was closed, 0 if it was disconnected
161  // on purpose
162 
163 
164  @author Andreas Beckermann <[email protected]>, Burkhard Lehner <[email protected]>
165 */
166 class KDEGAMESPRIVATE_EXPORT KMessageServer : public QObject
167 {
168  Q_OBJECT
169 
170 public:
171  /**
172  MessageIDs for messages from a client to the message server.
173  */
174  enum {
175  REQ_BROADCAST = 1,
176  REQ_FORWARD,
177  REQ_CLIENT_ID,
178  REQ_ADMIN_ID,
179  REQ_ADMIN_CHANGE,
180  REQ_REMOVE_CLIENT,
181  REQ_MAX_NUM_CLIENTS,
182  REQ_CLIENT_LIST,
183  REQ_MAX_REQ = 0xffff
184  };
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  //------------------------------ ID stuff
345 
346  /*
347  * The unique ID of this game
348  *
349  * @return int id
350  */
351  // int gameId() const;
352 
353  /*
354  * Application cookie. this identifies the game application. It
355  * help to distinguish between e.g. KPoker and KWin4
356  *
357  * @return the application cookie
358  */
359  // int cookie() const;
360 
361  //------------------------------ Message stuff
362 
363 public:
364  /**
365  * Sends a message to all connected clients.
366  * The message is NOT translated in any way. This method calls
367  * @ref KMessageIO::send for every client added.
368  */
369  virtual void broadcastMessage(const QByteArray &msg);
370 
371  /**
372  * Sends a message to a single client with the given ID.
373  * The message is NOT translated in any way.
374  * If no client with the given id exists, nothing is done.
375  * This is just a convenience method. You could also call
376  * @ref findClient (id)->send(msg) manually, but this method checks for
377  * errors.
378  */
379  virtual void sendMessage(quint32 id, const QByteArray &msg);
380 
381  /**
382  * Sends a message to a list of clients. Their ID is given in ids. If
383  * a client id is given more than once in the list, the message is also
384  * sent several times to that client.
385  * This is just a convenience method. You could also iterate over the
386  * list of IDs.
387  */
388  virtual void sendMessage(const QList<quint32> &ids, const QByteArray &msg);
389 
390 protected Q_SLOTS:
391  /**
392  * This slot receives all the messages from the @ref KMessageIO::received signals.
393  * It stores the messages in a queue. The messages are later taken out of the queue
394  * by @ref getReceivedMessage.
395  *
396  * NOTE: It is important that this slot may only be called from the signal
397  * @ref KMessageIO::received, since the sender() object is used to find out
398  * the client that sent the message!
399  */
400  virtual void getReceivedMessage(const QByteArray &msg);
401 
402  /**
403  * This slot is called whenever there are elements in the message queue. This queue
404  * is filled by @ref getReceivedMessage.
405  * This slot takes one message out of the queue and analyzes processes it,
406  * if it recognizes it. (See message types in the description of the class.)
407  * After that, the signal @ref messageReceived is emitted. Connect to that signal if
408  * you want to process other types of messages.
409  */
410  virtual void processOneMessage();
411 
412  //---------------------------- Signals
413 
414 Q_SIGNALS:
415  /**
416  * A new client connected to the game
417  * @param client the client object that connected
418  */
419  void clientConnected(KMessageIO *client);
420 
421  /**
422  * A network connection got broken. Note that the client will automatically get deleted
423  * after this signal is emitted. The signal is not emitted when the client was removed
424  * regularly.
425  *
426  * @param client the client which left the game
427  */
428  void connectionLost(KMessageIO *client);
429 
430  /**
431  * This signal is always emitted when a message from a client is received.
432  *
433  * You can use this signal to extend the communication server without subclassing.
434  * Just connect to this signal and analyze the message, if unknown is true.
435  * If you recognize a message and process it, set unknown to false, otherwise
436  * a warning message is printed.
437  *
438  * @param data the message data
439  * @param clientID the ID of the KMessageIO object that received the message
440  * @param unknown true, if the message type is not known by the KMessageServer
441  */
442  void messageReceived(const QByteArray &data, quint32 clientID, bool &unknown);
443 
444 protected:
445  /**
446  * @return A unique number which can be used as the id of a @ref KMessageIO. It is
447  * incremented after every call so if you need the id twice you have to save
448  * it anywhere. It's currently used to initialize newly connected clients only.
449  */
450  quint32 uniqueClientNumber() const;
451 
452 private:
453  std::unique_ptr<KMessageServerPrivate> const d;
454 };
455 
456 #endif
Q_SLOTSQ_SLOTS
Q_SIGNALSQ_SIGNALS
A server for message sending and broadcasting, using TCP/IP connections.
This file is part of the KDE documentation.
Documentation copyright © 1996-2023 The KDE developers.
Generated on Mon May 8 2023 03:49:44 by doxygen 1.8.17 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.