home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / SLAX 6.0.8 / slax-6.0.8.iso / slax / base / 006-devel.lzm / usr / include / kgame / kmessageserver.h < prev    next >
Encoding:
C/C++ Source or Header  |  2005-10-10  |  18.1 KB  |  493 lines

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