forked from Lupus590AtUni/Uni_NetworksAssignment
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NA_TCP.cpp
123 lines (89 loc) · 2.21 KB
/
NA_TCP.cpp
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
122
123
#include "NA_TCP.h"
#include "globals.h"
#include <iostream>
using std::cerr;
DWORD NA_TCP::threadFunc() //background recive
{
//Do any setup
while (!terminateRequested)
{
//TODO: UDP listen for messages and add to queue
}
//Do any cleanup
return 0;
}
NA_TCP::NA_TCP()
{
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
}
NA_TCP::~NA_TCP()
{
if (ready)
closesocket(sock);
}
bool NA_TCP::c(string address, string port)
{
if (!ready) //should call init first
return false;
addrinfo *addrInfoResult;
int result = getaddrinfo(address.c_str, port.c_str, &hints, &addrInfoResult); //looking for all servers which can do what I need
if (result != 0)
{
return false;
}
sock = socket(addrInfoResult->ai_family, addrInfoResult->ai_socktype, addrInfoResult->ai_protocol); //create the socket
int result = connect(sock, addrInfoResult->ai_addr, (int)addrInfoResult->ai_addrlen); //attempt to connect to the first result of getaddrinfo
//LOW: attempt connecton to other addresses
if (result != 0)
{
closesocket(sock);
return false;
}
freeaddrinfo(addrInfoResult);
if (sock == INVALID_SOCKET)
return false; //had a problem somewhere
//else
return true; //connection made
}
bool NA_TCP::init()
{
if (!ready)
{
//Init
if (!na_netMan.isReady())
{
if (!na_netMan.init())
return false; //na_netMan not ready and failed to init
}
//na_netMan is ready, do own init
}
//else already ready
ready = true;
return ready;
}
void NA_TCP::s(string str)
{
//LOW: special packing
send(sock, str.c_str, str.length, 0); //NOTE: check if loses /n
//+1 to length if it does
//somptom: tons of junk is appended to message
}
string NA_TCP::r()
{
string str;
queueCritSec.enter();//lock the queue
if (!reciveQueue.isEmpty())
{
str = reciveQueue.dequeue();//pull item from queue
}
queueCritSec.leave();//unlock the queue
//LOW:special unpacking
return string();
}
bool NA_TCP::hasMessage()
{
return !reciveQueue.isEmpty();
}