From 3f9ce9f54d342bfaba1f41bb0d6b18aa9cf11a43 Mon Sep 17 00:00:00 2001 From: LaG1924 <12997935+LaG1924@users.noreply.github.com> Date: Thu, 30 Jul 2020 04:34:25 +0500 Subject: Implemented async connection to server --- src/Game.cpp | 54 ++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 42 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/Game.cpp b/src/Game.cpp index c69ff5d..f0266d4 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -18,35 +18,61 @@ std::unique_ptr render; std::unique_ptr timer; EventListener listener; -void InitEvents() { - /* - * Network Events - */ +std::thread connThread; +std::unique_ptr connNc; +std::unique_ptr connGs; + +void ConnectionThreadExec() { + EventListener connListener; - listener.RegisterHandler("ConnectToServer", [](const Event & eventData) { + bool connRun = true; + + connListener.RegisterHandler("ConnectToServer", [](const Event& eventData) { auto data = eventData.get >(); //address,port,username if (std::get<0>(data) == "" || std::get<1>(data) == 0) LOG(FATAL) << "NOT VALID CONNECT-TO-SERVER EVENT"; - if (nc != nullptr) { + if (connNc != nullptr) { LOG(ERROR) << "Already connected"; return; } LOG(INFO) << "Connecting to server at address " + std::get<0>(data) + ":" + std::to_string(std::get<1>(data)) + " as " + std::get<2>(data); - PUSH_EVENT("Connecting",0); - gs = std::make_unique(); + PUSH_EVENT("Connecting", 0); + connGs = std::make_unique(); try { - nc = std::make_unique(std::get<0>(data), + connNc = std::make_unique(std::get<0>(data), std::get<1>(data), std::get<2>(data)); - } catch (std::exception &e) { + } + catch (std::exception& e) { LOG(WARNING) << "Connection failed"; PUSH_EVENT("ConnectionFailed", std::string(e.what())); - gs.reset(); + connGs.reset(); return; } LOG(INFO) << "Connected to server"; PUSH_EVENT("ConnectionSuccessfull", 0); - }); + }); + + connListener.RegisterHandler("Exit", [&](const Event&) { + connRun = false; + }); + + LoopExecutionTimeController timer(std::chrono::milliseconds(50)); + while (connRun) { + connListener.HandleAllEvents(); + timer.Update(); + } +} + +void InitEvents() { + /* + * Network Events + */ + + listener.RegisterHandler("ConnectionSuccessfull", [](const Event&) { + nc = std::move(connNc); + gs = std::move(connGs); + }); listener.RegisterHandler("Disconnect", [](const Event& eventData) { auto data = eventData.get(); @@ -186,6 +212,8 @@ void RunGame() { render = std::make_unique(900, 480, "AltCraft"); + connThread = std::thread(ConnectionThreadExec); + SetState(State::MainMenu); while (isRunning) { @@ -212,6 +240,8 @@ void RunGame() { } render.reset(); + + connThread.join(); } State GetState() { -- cgit v1.2.3