Now that we have threads our chat client becomes dead simple to implement.
The first consideration is how many threads we want to have.
We have 3 basic functions but only two of those are going to be blocking the main thread, therefore besides the main thread, we only need 1 more thread.
We will call this the user input thread.
Since we have determined that we want user input in it's own thread, lets create a function to deal with user input.
void HandleInput(void* Conn)
{
std::string data;
Platinum::Net::TCP::Connection* Remote = reinterpret_cast(Remote);
while(!quit)
{
std::getline(std::cin, data, '\n');
Platinum::Net::TCP::Send(Remote,data);
if(data == "/quit")
quit = true;
}
}
As you can see it's just a very simple loop that gathers data from std::in and sends it to the remote connection.
Our main section of code is really simple too.
We just create a new Connection, initialize it and connect it to our remote server.
Then we create the new thread, and pass it our Connection.
Concurrent to the thread creation we have a main loop which checks the connection for data received and takes a nap.
It's all just...
Net::TCP::Connection* Remote = new Net::TCP::Connection();
try{
Net::TCP::Initialize(Remote);
Net::TCP::Connect(Remote,IP,iPort);
Thread::Create(HandleInput,(void*)Remote);
}catch(Error(e)){
ProcessError(e);
}
while(!quit)
{
msg = Net::TCP::Recv(Remote);
std::cout << msg;
Thread::Yield();
}
Now of course we do cheat a little bit here, we are using a global variable called "quit" but since there is no easy way for us to setup inter-thread communications yet, a global variable will have to do.
Thats it folks, enjoy!
Our next library focus will be on graphics, but first we will write a simple game.
It will be a multi-user game, and it will be text based.
I recommend you get out your graph paper for the next chapter.
Mud and Muk, Dungeons and Cards.