-
Notifications
You must be signed in to change notification settings - Fork 0
/
Helper.cpp
84 lines (67 loc) · 1.69 KB
/
Helper.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
#include "Helper.h"
#include <string>
#include <iomanip>
#include <sstream>
using namespace std;
// recieves the type code of the message from socket (first byte)
// and returns the code. if no message found in the socket returns 0 (which means the client disconnected)
int Helper::getMessageTypeCode(SOCKET sc)
{
char* s = getPartFromSocket(sc, 3);
std::string msg(s);
if (msg == "")
return 0;
int res = std::atoi(s);
delete s;
return res;
}
// send data to socket
// this is private function
void Helper::sendData(SOCKET sc, std::string message)
{
const char* data = message.c_str();
if (send(sc, data, message.size(), 0) == INVALID_SOCKET)
{
throw std::exception("Error while sending message to client");
}
}
int Helper::getIntPartFromSocket(SOCKET sc, int bytesNum)
{
char* s = getPartFromSocket(sc, bytesNum, 0);
return atoi(s);
}
string Helper::getStringPartFromSocket(SOCKET sc, int bytesNum)
{
char* s = getPartFromSocket(sc, bytesNum, 0);
string res(s);
return res;
}
// recieve data from socket according byteSize
// this is private function
char* Helper::getPartFromSocket(SOCKET sc, int bytesNum)
{
return getPartFromSocket(sc, bytesNum, 0);
}
char* Helper::getPartFromSocket(SOCKET sc, int bytesNum, int flags)
{
if (bytesNum == 0)
{
return "";
}
char* data = new char[bytesNum + 1];
int res = recv(sc, data, bytesNum, flags);
if (res == INVALID_SOCKET)
{
std::string s = "Error while recieving from socket: ";
s += std::to_string(sc);
throw std::exception(s.c_str());
}
data[bytesNum] = 0;
return data;
}
string Helper::getPaddedNumber(int num, int digits)
{
std::ostringstream ostr;
ostr << std::setw(digits) << std::setfill('0') << num;
return ostr.str();
}