Пример #1
0
/**
*  @brief
*    Run client
*/
void RunClient()
{
	// Create client
	ChatClient cClient;

	// Create a client connection at host address 'localhost' (our local server) at port '4000'
	ChatClientConnection *pConnection = static_cast<ChatClientConnection*>(cClient.Connect("localhost", 4000));
	if (pConnection) {
		bool bActive = true;
		String sMessage;

		// Main loop
		System::GetInstance()->GetConsole().Print("Input text to send and press 'Enter'\nPress 'ESC' to exit the client\n");
		while (bActive) {
			// Let the system some time to process other system tasks etc.
			// If this isn't done the CPU usage is nearly up to 100%!
			System::GetInstance()->Sleep(1);

			// Update client
			if (pConnection->IsConnected()) {
				// Check keys
				if (System::GetInstance()->GetConsole().IsKeyHit()) {
					// Get key and interpret it as character, not number
					const wchar_t nCharacter = static_cast<wchar_t>(System::GetInstance()->GetConsole().GetCharacter());

					// Quit
					if (nCharacter == 27)
						bActive = false;

					// Message
					else if (nCharacter == 13) {
						// New line on the console, please
						System::GetInstance()->GetConsole().Print('\n');

						// Send the message
						pConnection->Send(sMessage, sMessage.GetLength() + 1);

						// Clear the message
						sMessage = "";

					// Character
					} else {
						// Add character to the message
						sMessage += nCharacter;

						// Output the character on the console
						System::GetInstance()->GetConsole().Print(nCharacter);
					}
				}
			} else {
				// Connection broken...
				System::GetInstance()->GetConsole().Print("Error: Connection to the server broken... press any key to exit\n");
				bActive = false;

				// Wait for the 'any key'
				System::GetInstance()->GetConsole().GetCharacter();
			}
		}

		// Shutdown our client
		pConnection->Disconnect();
	} else {
		// Error!
		System::GetInstance()->GetConsole().Print("Error: Could not connect to server... press any key to exit\n");

		// Wait for the 'any key'
		System::GetInstance()->GetConsole().GetCharacter();
	}
}