-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathClient.cpp
More file actions
108 lines (91 loc) · 2.87 KB
/
Client.cpp
File metadata and controls
108 lines (91 loc) · 2.87 KB
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
#include "Client.h"
WSADATA Client::wsaData;
ADDRINFO Client::hints;
ADDRINFO* Client::addrResult = NULL;
SOCKET Client::ConnectSocket = INVALID_SOCKET;
char Client::SendBuffer[512];
char Client::recvBuffer[2048];
User Client::User;
int Client::Initialize() {
int Result;
Result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (Result != 0) {
cout << "WSAStartup failed";
return 1;
}
//хинты
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET; //семейтво протоколов //ipv4 ethernet
hints.ai_socktype = SOCK_STREAM; //тип сокета
hints.ai_protocol = IPPROTO_TCP; //tcp протокол
//инит адреса
Result = getaddrinfo("localhost", "666", &hints, &addrResult);
if (Result != 0) {
cout << "GetAddrInfo failed";
freeaddrinfo(addrResult);
WSACleanup();
return 1;
}
ConnectSocket = socket(addrResult->ai_family, addrResult->ai_socktype, addrResult->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
cout << "Socket creation failed";
freeaddrinfo(addrResult);
WSACleanup();
return 1;
}
for (int Counter = 0; Counter < 5; Counter++) {
Result = connect(ConnectSocket, addrResult->ai_addr, (int) addrResult->ai_addrlen);
if (Result != SOCKET_ERROR) break;
if (Result == SOCKET_ERROR) {
cout << "Trying to connect...\n";
sleep_for(seconds(2));
continue;
} if (Counter == 4) {
cout << "Unable connect to server";
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
freeaddrinfo(addrResult);
WSACleanup();
return 0;
}
}
}
string Client::AskServer(string Command) {
int Result;
for (int i = 0; i < (int) strlen(SendBuffer); i++) {
SendBuffer[i] = ' ';
}
//send buffer string command
for (int i = 0; i < Command.length(); i++) {
SendBuffer[i] = Command[i];
}
//send command to server
Result = send(ConnectSocket, SendBuffer, (int) strlen(SendBuffer), 0);
if (Result == SOCKET_ERROR) {
cout << "Send failed";
closesocket(ConnectSocket);
freeaddrinfo(addrResult);
WSACleanup();
return "SOCKET_ERROR";
}
//receive server answer
recv(ConnectSocket, recvBuffer, 2048, 0);
string Buffer(recvBuffer);
memset(recvBuffer, 0, 2048);
return Buffer;
}
int Client::CloseConnection() {
//shutdown connection and close socket
int Result = shutdown(ConnectSocket, SD_SEND);
if (Result == SOCKET_ERROR) {
cout << "Shutdown error " << Result << endl;
closesocket(ConnectSocket);
freeaddrinfo(addrResult);
WSACleanup();
return 1;
}
closesocket(ConnectSocket);
freeaddrinfo(addrResult);
WSACleanup();
return 0;
}