-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.cpp
More file actions
101 lines (84 loc) · 2.26 KB
/
Client.cpp
File metadata and controls
101 lines (84 loc) · 2.26 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
#include "Client.h"
void Client::receiveMessages(SOCKET sock)
{
char buffer[1024];
while (true) {
int bytesReceived = recv(sock, buffer, sizeof(buffer), 0);
if (bytesReceived > 0) {
std::cout << std::string(buffer, bytesReceived);
}
else {
std::cout << "\nDisconnected from server.\n";
break;
}
}
}
int Client::StartClient()
{
std::string portBuff = "";
std::cout << "please specify server ip addres: ";
std::getline(std::cin, SERVER_IP);
std::cout << "\nplease specify server port: ";
std::getline(std::cin, portBuff);
SERVER_PORT = static_cast<WORD>(std::stoi(portBuff));
erStat = WSAStartup(MAKEWORD(2, 2), &WsaData);
if (erStat != 0) {
std::cout << "Error WinSock version initializaion #";
std::cout << WSAGetLastError();
return 1;
}
else
std::cout << "WinSock initialization is OK" << std::endl;
ClientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (ClientSocket == INVALID_SOCKET)
{
std::cout << "Error when initializing client socket. Closing";
closesocket(ClientSocket);
WSACleanup();
return 1;
}
else
std::cout << "Initializing client socket done!\n";
in_addr ip_to_num{};
erStat = inet_pton(AF_INET, SERVER_IP.c_str(), &ip_to_num);
if (erStat <= 0)
{
std::cout << "Error in IP translation to numeric format";
closesocket(ClientSocket);
WSACleanup();
return 1;
}
sockaddr_in servInfo;
ZeroMemory(&servInfo, sizeof(servInfo));
servInfo.sin_family = AF_INET;
servInfo.sin_port = htons(SERVER_PORT);
servInfo.sin_addr = ip_to_num;
if (connect(ClientSocket, (sockaddr*)&servInfo, sizeof(servInfo)) == SOCKET_ERROR) {
std::cerr << "Connection failed\n";
closesocket(ClientSocket);
WSACleanup();
return 1;
}
std::cout << "Connected to server.\n";
std::cout << "Enter username: ";
std::string username;
std::getline(std::cin, username);
send(ClientSocket, username.c_str(), username.size(), 0);
std::thread(&Client::receiveMessages, this, ClientSocket).detach();
std::string msg;
while (true) {
std::getline(std::cin, msg);
if (msg == "/quit") {
send(ClientSocket, "EndConnTrue!", 13, 0);
break;
}
else if (msg == "/help") {
send(ClientSocket, "!Help", 6, 0);
break;
}
send(ClientSocket, msg.c_str(), msg.size(), 0);
}
closesocket(ClientSocket);
WSACleanup();
return 0;
}