Example #1
0
void Session::Run()
{
    Command cmd;

    while (true)
    {
        mQueue.WaitAndPop(cmd);
        if (cmd == START)
        {
            cmd = NO_CMD;
            if (mTcpClient.Connect(mHostName, mTcpPort) == true)
            {
                Protocol proto;

                while (mInitialized)
                {
                    if (mTcpClient.DataWaiting(200U))
                    {
                        std::string payload;
                        if (mTcpClient.Recv(payload))
                        {
                            proto.Add(payload);
                            std::string data;
                            while (proto.Parse(data))
                            {
                            //    TLogNetwork("Found one packet with data: " + data);
                                std::vector<Reply> out;
                                std::uint32_t client_uuid = proto.GetDestUuid();

                                bool ret = mListener.Deliver(proto.GetSourceUuid(), client_uuid, data, out);
                                // Send synchronous data to the server
                                if (ret)
                                {
                                    Send(out);
                                }
                            }
                        }
                    }
                    else
                    {
                        //std::cout << "client wait timeout or failure" << std::endl;
                        mInitialized = IsConnected(); // determine origine of failure
                    }
                }
                mListener.Signal(net::IEvent::ErrDisconnectedFromServer);
                TLogNetwork("Client connection closed.");
            }
            else
            {
                TLogError("Client cannot connect to server.");
                mListener.Signal(net::IEvent::ErrCannotConnectToServer);
            }
        }
        else if (cmd == EXIT)
        {
            std::cout << "Exit client thread" << std::endl;
            return;
        }
    }
}