aboutsummaryrefslogtreecommitdiff
path: root/networkmanager.cpp
blob: 2568b694fdc790305d1d953722ec95ac5529bf53 (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include "networkmanager.h"

#include "datatypes.h"
#include "debug_functions.h"
#include "lobby.h"


NetworkManager::NetworkManager(AOApplication *parent) : QObject(parent)
{
  ao_app = parent;

  ms_socket = new QTcpSocket(this);
  server_socket = new QTcpSocket(this);

  QObject::connect(ms_socket, SIGNAL(readyRead()), this, SLOT(handle_ms_packet()));
  QObject::connect(server_socket, SIGNAL(readyRead()), this, SLOT(handle_server_packet()));
}

NetworkManager::~NetworkManager()
{

}

void NetworkManager::connect_to_master()
{
  ms_socket->close();
  ms_socket->abort();

  ms_socket->connectToHost(ms_hostname, ms_port);
}

void NetworkManager::connect_to_server(server_type p_server)
{
  server_socket->close();
  server_socket->abort();

  server_socket->connectToHost(p_server.ip, p_server.port);
}

void NetworkManager::ship_ms_packet(QString p_packet)
{
  ms_socket->write(p_packet.toLocal8Bit());
}

void NetworkManager::ship_server_packet(QString p_packet)
{
  server_socket->write(p_packet.toLocal8Bit());
}

void NetworkManager::handle_ms_packet()
{
  char buffer[16384] = {0};
  ms_socket->read(buffer, ms_socket->bytesAvailable());

  QString in_data = buffer;

  if (!in_data.endsWith("%"))
  {
    ms_partial_packet = true;
    ms_temp_packet += in_data;
    return;
  }

  else
  {
    if (ms_partial_packet)
    {
      in_data = ms_temp_packet + in_data;
      ms_temp_packet = "";
      ms_partial_packet = false;
    }
  }

  QStringList packet_list = in_data.split("%", QString::SplitBehavior(QString::SkipEmptyParts));

  for (QString packet : packet_list)
  {    
    AOPacket *f_packet = new AOPacket(packet);

    ao_app->ms_packet_received(f_packet);

    delete f_packet;
  }
}

void NetworkManager::handle_server_packet()
{
  char buffer[16384] = {0};
  server_socket->read(buffer, server_socket->bytesAvailable());

  QString in_data = buffer;

  if (!in_data.endsWith("%"))
  {
    partial_packet = true;
    temp_packet += in_data;
    return;
  }

  else
  {
    if (partial_packet)
    {
      in_data = temp_packet + in_data;
      temp_packet = "";
      partial_packet = false;
    }
  }

  QStringList packet_list = in_data.split("%", QString::SplitBehavior(QString::SkipEmptyParts));

  for (QString packet : packet_list)
  {
    AOPacket *f_packet = new AOPacket(packet);

    ao_app->server_packet_received(f_packet);

    delete f_packet;
  }
}