To write a client application for kNet, proceed through the following steps:
For each MessageConnection that is created, the application needs to associate a listener object to manage the messages that are received.
When a new message comes in from the other end of the connection, the MessageConnection worker thread places it into an internal message queue. To process this queue, the application should periodically call MessageConnection::ProcessMessages. This will cause IMessageHandler::HandleMessage to be called for each message in the queue, after which the message is destroyed.
This concept of processing incoming messages through a message listener is demonstrated in the next sample.
#include "kNet.h" // Define a MessageID for our a custom message. const message_id_t cHelloMessageID = 10; // This object gets called whenever new data is received. class MessageListener : public IMessageHandler { public: void HandleMessage(MessageConnection *source, message_id_t id, const char *data, size_t numBytes) { if (id == cHelloMessageID) { // Read what we received. DataDeserializer dd(data, numBytes); std::cout << "Server says: " << dd.ReadString() << std::endl; source->Disconnect(); } } }; int main(int argc, char **argv) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " server-ip" << std::endl; return 0; } Network network; MessageListener listener; const unsigned short cServerPort = 1234; MessageConnection *connection = network.Connect(argv[1], cServerPort, SocketOverUDP, &listener); // Run the main client loop. connection->RunModalClient(); return 0; }
1.7.1