I had considered skipping creating a chat client at this stage because telnet serves our purposes so much better than anything we can create right now.
The main problem with creating a chat client right now is that we do not have threading in the library yet, interestingly enough though our next library section will cover threads.
The reason we need threads is that a client is composed of 3 heavy sections, one of which HAS to block.
We have Network, Processing and User Input stages, these stages are all non blocking with the exception of waiting on user input.
However we do need a test harness for every section of the library, therefore we will create a TCP Chat Client program, the purpose of which is to test the TCP::Connect functionality of the library.
Since we aren't messing with threads at all this program is greatly simplified.
The process is as follows.
#1 Get a socket.
#2 Connect socket to remote server.
#3 Recv messages from server
#4 Accept user input
#5 Send user input
#6 Repeat steps 3, 4 and 5 until told to quit
With that said the code then should be relatively easy, however since we cannot run the networking in it's own thread yet, what effectively happens is that the program stalls at step 4 so no new data can be received. If this happens we have the potential for the chat buffer to overfill and parts of the conversation may be lost. Now you can see why I said telnet is a better chat client at this stage.
Onward to the code!
First thing we want is to create an instance of the TCP::Connection class which will hold our socket.
TCP::Connection* MyConn = new TCP::Connection();
Next we need to initialize the Connection which will assign the connection a socket.
TCP::Initialize(MyConn);
Our next step is to connect our Connection class to a remote server somewhere
TCP::Connect(MyConn,IP,iPort);
Then we need to set it to non-blocking
TCP::SetBlocking(MyConn,false);
Now comes our main loop, which is comprised of 3 stages.
First we want to receive data from the server.
try{
msg = TCP::Recv(MyConn);
std::cout << msg;
}catch(Platinum::Error e){
ProcessError(e);
quit = true;
}
Next we check for user input
std::getline(std::cin, msg, '\n');
And finally we send that input prior to looping again.
try{
TCP::Send(MyConn,msg);
}catch(Platinum::Error e){
ProcessError(e);
quit = true;
}
Of course we want to be able to quit the application gracefully so lets check the input and see if it contains a command to quit.
if(msg == "/quit")
quit = true;
Well folks there you have it, a very, very simple TCP Chat Client that you can call your own.
We are now done with the Platinum::Net library. We have wrapped both TCP and UDP in simple easy to use interfaces that are completely cross platform, intuitive to use.
Next we will be working with threads in Platinum::Thread