summaryrefslogtreecommitdiffstats
path: root/src/ThreadNetwork.cpp
blob: f734c0ca6e0a77239e1994f98f646188199aaf88 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include "ThreadNetwork.hpp"

ThreadNetwork::ThreadNetwork() {

}

ThreadNetwork::~ThreadNetwork() {	
}

void ThreadNetwork::Execute() {
	EventListener listener;

    listener.RegisterHandler(EventType::Exit, [this] (EventData eventData) {
        isRunning = false;
    });

	listener.RegisterHandler(EventType::ConnectToServer, [this](EventData eventData) {
		auto data = std::get<ConnectToServerData>(eventData);
		if (data.address == "" || data.port == 0)
			LOG(FATAL) << "NOT VALID CONNECT-TO-SERVER EVENT";
		if (nc != nullptr) {
			LOG(ERROR) << "Already connected";
			return;
		}
		LOG(INFO) << "Connecting to server";
        EventAgregator::PushEvent(EventType::Connecting, ConnectingData{});
		try {
			nc = new NetworkClient(data.address, data.port, "HelloOne");
		} catch (std::exception &e) {
			LOG(WARNING) << "Connection failed";
			EventAgregator::PushEvent(EventType::ConnectionFailed, ConnectionFailedData{e.what()});
            return;
		}
		LOG(INFO) << "Connected to server";
		EventAgregator::PushEvent(EventType::ConnectionSuccessfull, ConnectionSuccessfullData{nc});
	});

    listener.RegisterHandler(EventType::Disconnect, [this](EventData eventData) {
        auto data = std::get<DisconnectData>(eventData);
        EventAgregator::PushEvent(EventType::Disconnected, DisconnectedData{ data.reason });
        LOG(INFO) << "Disconnected: " << data.reason;
        delete nc;
        nc = nullptr;
    });

    listener.RegisterHandler(EventType::NetworkClientException, [this](EventData eventData) {
        auto data = std::get<NetworkClientExceptionData>(eventData);
        EventAgregator::PushEvent(EventType::Disconnect, DisconnectData{ data.what });
    });

    LoopExecutionTimeController timer(std::chrono::milliseconds(16));
	while (isRunning) {
		listener.HandleEvent();
        
        timer.Update();
	}
    delete nc;
}