-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.cpp
More file actions
110 lines (90 loc) · 2.83 KB
/
client.cpp
File metadata and controls
110 lines (90 loc) · 2.83 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
109
110
#include <Windows.h>
#include <iostream>
#include <string>
#define BUFSIZE 1024
using namespace std;
int main(int argc, char* argv[]) {
if (argc != 2) {
cerr << "Usage: " << argv[0] << " <client number>" << endl;
return 1;
}
int clientNum = atoi(argv[1]);
if (clientNum < 0) {
cerr << "Client number must be non-negative" << endl;
return 1;
}
HANDLE hPipe;
BOOL fSuccess;
DWORD dwRead;
char buffer[BUFSIZE];
// Формирование имени канала для данного клиента
string pipeName = "\\\\.\\pipe\\worddist_pipe_" + to_string(clientNum);
// Подключение к именованному каналу
while (true) {
hPipe = CreateFileA(
pipeName.c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hPipe != INVALID_HANDLE_VALUE) {
break;
}
// обработка ошибок подключения
if (GetLastError() != ERROR_PIPE_BUSY) {
cerr << "Failed to connect to pipe. GLE=" << GetLastError() << endl;
return 1;
}
// освобождение
if (!WaitNamedPipeA(pipeName.c_str(), 20000)) {
cerr << "Could not open pipe: 20 second wait timed out" << endl;
return 1;
}
}
cout << ">>> Client " << clientNum << " connected to server <<<" << endl;
//
while (true) {
// чтение данных от сервера
fSuccess = ReadFile(
hPipe,
buffer,
BUFSIZE,
&dwRead,
NULL);
// обработка ошибок чтения
if (!fSuccess || dwRead == 0) {
if (GetLastError() == ERROR_BROKEN_PIPE) {
cout << "Server disconnected." << endl;
}
else {
cerr << "Read error. GLE=" << GetLastError() << endl;
}
break;
}
buffer[dwRead] = '\0';
string word(buffer);
// проверка команды завершения работы
if (word == "END") {
cout << "Received termination command." << endl;
break;
}
cout << "Received word: " << word << endl;
// отправка подтверждения серверу
string ack = "ACK_" + to_string(clientNum);
fSuccess = WriteFile(
hPipe,
ack.c_str(),
ack.size(),
&dwRead,
NULL);
if (!fSuccess) {
cerr << "Write error. GLE=" << GetLastError() << endl;
break;
}
}
CloseHandle(hPipe);
cout << "Client " << clientNum << " shutting down." << endl;
return 0;
}