-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.cpp
More file actions
804 lines (746 loc) · 32.4 KB
/
Copy pathClient.cpp
File metadata and controls
804 lines (746 loc) · 32.4 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <atomic> // For atomic<bool>
#include <stack>
#include <algorithm> // For remove
#include <cstring> // For memset
#include <winsock2.h> // For socket functions on Windows
#include <ws2tcpip.h> // For inet_addr
#include <windows.h> // For Sleep
#include "md5.h"
#include "Body.h"
#include "Packet.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
using namespace std;
struct Record {
string msg;
// 构造函数
Record(const std::string& n) : msg(n) {}
};
class Counter {
private:
int value;
public:
Counter() : value(0) {}
int getID() {
value++;
// overflow then reset to 0
if (value == 256) {value = 0;}
return value; // 返回当前计数器的值
}
};
struct serverInfo {
int socket; // 通过connect函数返回值赋值
string IP; // 手动赋值
int port;
int serverId;
bool connect; // 手动
sockaddr_in svrAddr; // 在connect函数体中赋值
Counter requestId;
};
// 全局变量
mutex mtx;
condition_variable res, getList;
queue<Record> msgQueue;
vector<serverInfo> servers;
bool exitFlag = false; // 用于控制消费者线程退出
atomic<bool> waitList = false; // get list = true didn't = false
bool isTcp = true;
atomic<bool> stopWaiting = false;
stack<int> Ids;
int currentClientNum;
// 生产者
void ReceiveMsg(serverInfo& info) {
size_t bytesReceived;
char buffer[1024] = {0};
while (info.connect) {
if(isTcp){
bytesReceived = recv(info.socket, buffer, sizeof(buffer), 0);
}
else{
sockaddr_in svrAddr;
int addrLen = sizeof(svrAddr);
bytesReceived = recvfrom(info.socket, buffer, sizeof(buffer), 0, (sockaddr*)&svrAddr, &addrLen);
}
if (bytesReceived > 0) {
buffer[bytesReceived] = '\0';
cout << "[Byte Num] = " << bytesReceived << endl;
cout << "[Info] Received from server " << info.serverId << ": " << buffer << endl;
string recvMsg(buffer, 1024);
unique_lock<mutex> msgLock(mtx);
msgQueue.push(Record(recvMsg)); // 将收到的消息放入队列
res.notify_all(); // 通知消费者可以处理消息
} else if (bytesReceived == 0) {
cout << "[Info] Connection closed by the server " << info.serverId << endl;
break; // 退出循环
} else {
cout << "[Error] Failed to receive data from server " << info.serverId << ", error code: " << WSAGetLastError() << endl;
break; // 退出循环
}
}
// 关闭连接
info.connect = false;
}
void processCityName(char* data);
void processWeatherData(char* data);
int processClientData(char* data);
// 消费者
void ProcessMsg() {
string stuId = to_string(STUID_CLIENT);
while (!exitFlag) {
unique_lock<mutex> msgLock(mtx);
res.wait(msgLock, []{ return !msgQueue.empty() || exitFlag; }); // 等待直到有消息或退出信号
while (!msgQueue.empty()) {
Record Record = msgQueue.front();
msgQueue.pop();
msgLock.unlock(); // 解锁
// cout << "[Consumer] Processing message: " << endl;
cout << "[Client] Get a new message " << endl;
const char* ptr = Record.msg.c_str();
Packet Packet(ptr,stuId);
// Packet.printPacketInfo();
Type packetType = Packet.getType();
if(packetType == Type::RESPONSE){ // get list success
const int bodyType = Packet.getBody().getType();
char* ptr = Packet.getBody().toString().data();
int sequence = Packet.getBody().getSequence();
if(bodyType == 1) {processCityName(ptr);}
else if (bodyType == 2) {processWeatherData(ptr);}
else if(bodyType == 3) {
currentClientNum = processClientData(ptr);
if((int)Ids.top() == sequence){
Ids.pop();
waitList = true;
getList.notify_one();
}
} else if (bodyType == 4) {
cout << "[Info] Send Msg to client :" << ptr[0] << " ";
cout << (ptr[1] ? "Succeed" : "Failed") << endl;
}
} else if (packetType == Type::INDICATION){
const int bodyType = Packet.getBody().getType();
char* ptr = Packet.getBody().toString().data();
// 这是大端
uint16_t msgLength = Packet.getBody().getLength();
// 大端 0x12 0x 34, 小端 0x34 0x12
// ptr = ptr + 2; // 新的消息字段入口
if(bodyType == 1){
size_t offset = 4;
cout << "+******************************************+" << endl;
cout << "[Info] Msg from client " << (int)ptr[offset] << ":";
for(int i = 1; i < msgLength; i++){
cout << ptr[i+offset];
}
cout << endl;
cout << "+******************************************+" << endl;
} else if (bodyType == 2 || bodyType == 3) { // 检查是否为指示类型2
size_t offset = 4;
// 解析字段
uint8_t clientId = static_cast<uint8_t>(ptr[offset++]); // 客户端编号
// 客户端 IP 地址
uint32_t clientIp = (static_cast<uint8_t>(ptr[offset]) << 24) |
(static_cast<uint8_t>(ptr[offset + 1]) << 16) |
(static_cast<uint8_t>(ptr[offset + 2]) << 8) |
static_cast<uint8_t>(ptr[offset + 3]);
offset += sizeof(uint32_t);
// 客户端端口
uint16_t clientPort = (static_cast<uint8_t>(ptr[offset]) << 8) |
(static_cast<uint8_t>(ptr[offset + 1]));
// 输出解析后的信息
if(bodyType == 2)
cout << "[Info] New Client Connected:" << endl;
else
cout << "[Info] Client Disconnected:" << endl;
cout << "+------------------------------------------+" << endl;
cout << "| Client ID | IP Address | Port |" << endl;
cout << "+------------------------------------------+" << endl;
cout << "| " << setw(10) << static_cast<int>(clientId) << " | "
<< setw(3) << ((clientIp >> 24) & 0xFF) << "."
<< setw(3) << ((clientIp >> 16) & 0xFF) << "."
<< setw(3) << ((clientIp >> 8) & 0xFF) << "."
<< setw(3) << (clientIp & 0xFF) << " | "
<< setw(8) << clientPort << " |" << endl;
cout << "+------------------------------------------+" << endl;
} else if (bodyType == 4) { // 检查是否为指示类型4
size_t offset = 4;
// 解析字段
char type_ = ptr[0 + offset];
int8_t longitude_interger_ = ptr[1 + offset];
uint8_t longitude_decimal_ = ptr[2 + offset];
int8_t latitude_interger_ = ptr[3 + offset];
uint8_t latitude_decimal_ = ptr[4 + offset];
uint8_t warningLevel_ = ptr[5 + offset];
string month_(ptr + 6 + offset, 2);
string day_(ptr + 8 + offset, 2);
string hour_(ptr + 10 + offset, 2);
string minute_(ptr + 12 + offset, 2);
string location_(ptr + 14 + offset, 10);
cout << "Get Weather Warning" << endl;
cout << "Type: " << type_ << endl;
cout << "Longitude: " << static_cast<int>(longitude_interger_) << "." << static_cast<int>(longitude_decimal_) << endl;
cout << "Latitude: " << static_cast<int>(latitude_interger_) << "." << static_cast<int>(latitude_decimal_) << endl;
cout << "Warning Level: " << static_cast<int>(warningLevel_) << endl;
cout << "Time: " << month_ << " " << day_ << " " << hour_ << ":" << minute_ << endl;
cout << "Location: " << location_ << endl;
}
}
msgLock.lock(); // 锁定以处理下一个消息
}
}
}
int connect(serverInfo& info) {
int svrSocket;
struct sockaddr_in svrAddr;
if(isTcp)
svrSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
else
svrSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (svrSocket == INVALID_SOCKET) {
cout << "[Error] Failed to create socket" << endl;
WSACleanup(); // 清理 Winsock
return false;
}
memset(&svrAddr, 0, sizeof(svrAddr));
svrAddr.sin_family = AF_INET;
svrAddr.sin_port = htons(info.port);
if(isTcp)
svrAddr.sin_addr.s_addr = inet_addr(info.IP.c_str());
else
inet_pton(AF_INET, info.IP.c_str(), &svrAddr.sin_addr);
if (connect(svrSocket, (struct sockaddr*)&svrAddr, sizeof(svrAddr)) == SOCKET_ERROR) {
cout << "[Error] Connection failed" << endl;
closesocket(svrSocket); // 关闭 socket
return INVALID_SOCKET;
}
info.svrAddr = svrAddr;
cout << "[Info] Server " << info.serverId << " connected to server at " << info.IP << ":" << info.port << endl;
return svrSocket;
}
void sendC(serverInfo& info, char* msg, int length){
if(isTcp)
send(info.socket, msg, length, 0);
else
sendto(info.socket, msg, length, 0, (sockaddr*)&info.svrAddr, sizeof(info.svrAddr));
}
void close(serverInfo& info) {
closesocket(info.socket);
}
string packStr(Type pacType, int bodyType, string& bodyStr, string stuId, int& length, int msgId){
vector<uint8_t> bodyVector(bodyStr.begin(), bodyStr.end());
string bodyContent = Body(static_cast<uint8_t>(msgId),static_cast<uint8_t>(bodyType),bodyVector).toString();
string studentId = to_string(STUID_CLIENT);
Packet packet(pacType, bodyContent, studentId);
length = (int)packet.getLength()+36; // 把这个包体长度拿出去,之后考虑+5 20bytes
return packet.toString();
}
void StrToC(string& str, char* out, int length){
for(int i=0; i < length; i++){
out[i] = str[i];
}
}
template <typename T>
T getIn(T min, T max) {
T value;
string input;
while (true) {
cout << "Please enter a value between " << min << " and " << max << ": ";
getline(cin, input);
try {
// Handle bool type input separately
if constexpr (is_same<T, bool>::value) {
if (input == "1" || input == "true") {
return true;
} else if (input == "0" || input == "false") {
return false;
} else {
cout << "Invalid input, please enter 0 or 1, or true or false." << endl;
continue;
}
}
// Convert other types
value = static_cast<T>(stod(input));
// Check if the value is within the range
if (value >= min && value <= max) {
return value;
} else {
cout << "The input value is out of range, please try again." << endl;
}
} catch (const invalid_argument& e) {
cout << "Invalid input, please enter a number." << endl;
} catch (const out_of_range& e) {
cout << "The input value is out of range, please try again." << endl;
}
}
}
void printMenu() {
this_thread::sleep_for(chrono::milliseconds(200)); // 给其他线程机会输出
unique_lock<mutex> lock(mtx);
cout << setw(40) << left << "HELLO! WELCOME TO THE MENU, SELECT YOUR CHOICE!" << endl;
cout << "+------------------------------------------+" << endl;
cout << "| " << setw(40) << left << "[0] CONNECT the server with IP and port." << " |" << endl;
cout << "| " << setw(40) << left << "[1] DISCONNECT the server with ID." << " |" << endl;
cout << "| " << setw(40) << left << "[2] GET THE CITY ID" << " |" << endl;
cout << "| " << setw(40) << left << "[3] GET THE WEATHER INFO" << " |" << endl;
cout << "| " << setw(40) << left << "[4] GET THE Clients LIST" << " |" << endl;
cout << "| " << setw(40) << left << "[5] SEND THE MESSAGE TO Client" << " |" << endl;
cout << "| " << setw(40) << left << "[6] QUIT" << " |" << endl;
cout << "+------------------------------------------+" << endl;
lock.unlock();
}
void printSvrInfo(vector<serverInfo>& svrInfos){
bool isFirst = true;
for(auto &svr : svrInfos){
if(isFirst){
cout << "------------------------------" << endl; // 分隔符
isFirst = false;
}
cout << "Server ID: " << svr.serverId << endl;
cout << "Socket: " << svr.socket << endl;
cout << "IP Address: " << svr.IP << endl;
cout << "Port: " << svr.port << endl;
cout << "Connected: " << (svr.connect ? "Yes" : "No") << endl;
// 输出 sockaddr_in 结构的信息
cout << "Server Address: "
<< inet_ntoa(svr.svrAddr.sin_addr) << ":"
<< ntohs(svr.svrAddr.sin_port) << endl;
cout << "------------------------------" << endl; // 分隔符
}
}
void readFourDigits(char (&arr)[4]) {
string input;
while (true) {
cout << "Please enter a four-digit number: ";
cin >> input;
if (input.length() == 4) { strcpy(arr, input.c_str()); break;}
else {cout << "Invalid input. Please ensure you enter a four-digit number." << endl;}
}
}
void quitHandler(){
string input;
cout << "stopwaiting" << stopWaiting << " waitlist" << waitList << endl;
cout << "+------------------------------------------+" << endl;
cout << "|Press 'q' to quit waiting and back to Menu|" << endl;
cout << "|Press 'c' to check if you got the list |" << endl;
cout << "+------------------------------------------+" << endl;
while (true) {
getline(cin, input);
cout << "stopwaiting" << stopWaiting << " waitlist" << waitList << endl;
if(input == "q"){
stopWaiting = true;
getList.notify_all();
break;
}
else if(input == "c"){
if(waitList ){
cout << "List get success" << endl;
break;
} else {
cout << "Still not get" << endl;
}
}
}
}
int processClientData(char* data) {
struct Client {
uint8_t id;
uint32_t address;
uint16_t port;
};
size_t offset = 4;
uint8_t clientCount = static_cast<uint8_t>(data[offset++]);
vector<Client> clients;
for (uint8_t i = 0; i < clientCount; ++i) {
Client client;
client.id = data[offset];
offset += 1;
uint32_t addr = (static_cast<uint8_t>(data[offset]) << 24) |
(static_cast<uint8_t>(data[offset + 1]) << 16) |
(static_cast<uint8_t>(data[offset + 2]) << 8) |
static_cast<uint8_t>(data[offset + 3]);
client.address = addr;
offset += sizeof(client.address);
client.port = (static_cast<uint8_t>(data[offset]) << 8) |
(static_cast<uint8_t>(data[offset + 1]));
offset += sizeof(client.port);
clients.push_back(client);
}
cout << "+------------------------------------------+" << endl;
cout << "| Number of online clients: "
<< setw(10) << setfill(' ') << static_cast<int>(clientCount)
<< " |" << endl;
cout << "+------------------------------------------+" << endl;
cout << "| Client ID | IP Address | Port |" << endl;
cout << "+------------------------------------------+" << endl;
for (const auto& client : clients) {
cout << "| " << setw(10) << static_cast<int>(client.id) << " | "
<< setw(3) << ((client.address >> 24) & 0xFF) << "."
<< setw(3) << ((client.address >> 16) & 0xFF) << "."
<< setw(3) << ((client.address >> 8) & 0xFF) << "."
<< setw(3) << (client.address & 0xFF) << " | "
<< setw(8) << client.port << " |" << endl;
}
cout << "+------------------------------------------+" << endl;
cout << endl;
return clientCount;
}
void processWeatherData(char* data) {
// Extracting weather parameters from the character array
size_t offset = 4;
int8_t airTemperature = data[0 + offset]; // Air temperature, -255 to 255
uint8_t weatherCondition = static_cast<uint8_t>(data[1 + offset]); // Weather condition flag, 1 to 3
uint8_t windDirection = static_cast<uint8_t>(data[2 + offset]); // Wind direction, 1 to 4
uint8_t windStrength = static_cast<uint8_t>(data[3 + offset]); // Wind strength, 0 to 20
uint8_t humidity = static_cast<uint8_t>(data[4 + offset]); // Humidity, 0 to 100
// Output weather data
cout << "Weather Data:\n";
cout << "Air Temperature: " << static_cast<int>(airTemperature) << "°C\n";
cout << "Weather Condition: " << static_cast<int>(weatherCondition) << " (1: Clear, 2: Overcast, 3: Rainy)\n";
cout << "Wind Direction: " << static_cast<int>(windDirection) << " (1: East, 2: West, 3: South, 4: North)\n";
cout << "Wind Strength: " << static_cast<int>(windStrength) << "\n";
cout << "Humidity: " << static_cast<int>(humidity) << "%\n";
}
// 处理城市名称的函数
void processCityName(char* data) {
string chineseName(data, 10);
string englishName(data + 10, 20);
const int chineseNameWidth = 10; // 中文名宽度
const int englishNameWidth = 15; // 英文名宽度
cout << "+----------+---------------+" << endl;
cout << "| Receive CityName: |" << endl;
cout << "+----------+---------------+" << endl;
cout << "| 中文名 | 英文名 |" << endl;
cout << "+----------+---------------+" << endl;
cout << "| " << setw(chineseNameWidth) << chineseName << " | " << setw(englishNameWidth-1) << englishName << " |" << endl;
cout << "+----------+---------------+" << endl;
}
int main() {
string svrIP;
int svrPort;
char cityCode[4] = {'0', '5', '7', '1'};
vector<thread> threads;
Counter svrId;
// init wsadata
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
cout << "[Error] WSAStartup failed with error: " << result << endl;
return -1; // 退出程序
}
// 启动消费者线程
thread consumerThread(ProcessMsg);
int choice;
while(1){
printMenu();
choice = getIn<int>(0, 6);
switch (choice){
case 0:{ // 连接
// 没有写避免对同一个ip:port的重复连接检查
cout << "Input your ip addr:";
cin >> svrIP;
cout << "Input your port num" << endl;
getchar();
svrPort = getIn<int>(0,65535);
// 本来想把svr的初始化全部放在connect函数外侧,但是不得不妥协在connect中初始化svr的addr成员
serverInfo svr;
svr.IP = svrIP;
svr.port = svrPort;
svr.socket = connect(svr);
if (svr.socket != INVALID_SOCKET) {
svr.connect = true;
svr.serverId = svrId.getID();
servers.push_back(svr);
}
if(false){
string msg = "";
cout << "Input your message to send:" << endl;
char *cMsg;
int length;
// bodyType 5 = try to connect UDP
string out = packStr(Type::REQUEST, 5, msg, to_string(STUID_CLIENT), length, svr.requestId.getID());
StrToC(out, cMsg, length+0);
sendC(svr, cMsg, length+0);
threads.emplace_back(ReceiveMsg, ref(svr));
break;
}
threads.emplace_back(ReceiveMsg, ref(svr));
break;
}
case 1:{ // 断开连接
if(servers.empty()) {
cout << "No server connect" << endl;
break;
}
cout << "Choose a server " << endl;
printSvrInfo(servers);
cout << "Input Server ID to disconnect or 0 to quit" << endl;
int disId = getIn<int>(0,65535);
if(!disId) break; // 0 = break
auto it = remove_if(servers.begin(), servers.end(), [disId](const serverInfo& server) {
return server.serverId == disId; // 条件:根据输入的 serverId
});
// 检查是否找到并移除服务器
if (it != servers.end()) {
it->connect = false;
closesocket(it->socket);
servers.erase(it, servers.end());
cout << "Server with ID " << disId << " disconnected." << endl;
} else {
cout << "Server ID " << disId << " not found." << endl;
}
// 输出当前服务器信息
if(!servers.empty()) {
cout << "Updated server list:" << endl;
printSvrInfo(servers);
} else cout << "Now no server connect!" << endl;
break;
}
case 2:{ // 获取 city name
if(servers.empty()) {
cout << "No server connect" << endl;
break;
}
cout << "Choose a server " << endl;
printSvrInfo(servers);
cout << "Input Server ID to request cityName or 0 to quit" << endl;
int svrId = getIn<int>(0,65535);
if(!svrId) break; // 0 = break
auto it = find_if(servers.begin(), servers.end(), [svrId](const serverInfo& server) {
return server.serverId == svrId; // 条件:根据输入的 serverId
});
// 检查是否找到
if (it != servers.end()) { // find success
cout << "Input city code:" << endl;
readFourDigits(cityCode);
getchar();
cout << cityCode[0] << cityCode[1] << cityCode[2] << cityCode[3] << endl;
string msg = cityCode;
int length;
// bodyType 1 = getcityID
string out = packStr(Type::REQUEST, 1, msg, to_string(STUID_CLIENT), length, it->requestId.getID());
for(int i = 0;i < length+0; i++)
cout << (int)out[i] << "|";
cout << endl;
char *cMsg = new char[length+0];
StrToC(out, cMsg, length+0);
for(int i = 0;i < length+0; i++)
cout << (int)cMsg[i] << "|";
cout << endl;
serverInfo &svr = *it;
sendC(svr, cMsg, length+0);
threads.emplace_back(ReceiveMsg, ref(svr));
Sleep(500); // 添加0.3秒的延迟
} else {
cout << "Server ID " << svrId << " not found." << endl;
}
break;
}
case 3:{ // 获取气象信息
if(servers.empty()) {
cout << "No server connect" << endl;
break;
}
cout << "Choose a server " << endl;
printSvrInfo(servers);
cout << "Input Server ID to request cityWeather or 0 to quit" << endl;
int svrId = getIn<int>(0,65535);
if(!svrId) break; // 0 = break
auto it = find_if(servers.begin(), servers.end(), [svrId](const serverInfo& server) {
return server.serverId == svrId; // 条件:根据输入的 serverId
});
// 检查是否找到
if (it != servers.end()) { // find success
int year, month, day;
cout << "Input year:";
year = getIn<int>(1999, 2099);
cout << "Input month:";
month = getIn<int>(0, 12);
cout << "Input day:";
day = getIn<int>(0, 31);
ostringstream oss;
oss << year << setw(2) << setfill('0') << month << setw(2) << setfill('0') << day;
string dateString = oss.str();
cout << "Input city code:" << endl;
readFourDigits(cityCode);
getchar();
cout << cityCode[0] << cityCode[1] << cityCode[2] << cityCode[3] << endl;
string msg = cityCode+dateString;
int length;
// bodyType 2 = getcitywether
string out = packStr(Type::REQUEST, 2, msg, to_string(STUID_CLIENT), length, it->requestId.getID());
char *cMsg = new char[length+0];
StrToC(out, cMsg, length+0);
for(int i = 0;i < length+0; i++)
cout << (int)cMsg[i] << "|";
cout << endl;
serverInfo &svr = *it;
sendC(svr, cMsg, length+0);
threads.emplace_back(ReceiveMsg, ref(svr));
Sleep(500); // 添加0.3秒的延迟
} else {
cout << "Server ID " << svrId << " not found." << endl;
}
break;
}
case 4:{ // 获取客户端list
if(servers.empty()) {
cout << "No server connect" << endl;
break;
}
cout << "Choose a server to get the list of clients" << endl;
printSvrInfo(servers);
cout << "Input Server ID to request cilentlist or 0 to quit" << endl;
int svrId = getIn<int>(0,65535);
if(!svrId) break; // 0 = break
auto it = find_if(servers.begin(), servers.end(), [svrId](const serverInfo& server) {
return server.serverId == svrId; // 条件:根据输入的 serverId
});
// 检查是否找到
if (it != servers.end()) { // find success
string msg = "123456789";
int length;
// bodyType 3 = getclientlist
int requestId = it->requestId.getID();
string out = packStr(Type::REQUEST, 3, msg, to_string(STUID_CLIENT), length, requestId);
char *cMsg = new char[length+0];
StrToC(out, cMsg, length+0);
for(int i = 0;i < length+0; i++)
cout << (int)cMsg[i] << "|";
cout << endl;
waitList = false; // send 之前就 reset waitlist
stopWaiting = false; // send 之前就 reset stopwaiting
serverInfo &svr = *it;
sendC(svr, cMsg, length+0);
threads.emplace_back(ReceiveMsg, ref(svr));
{
cout << "Push id = " << requestId << endl;
Ids.push(requestId);
cout << "Wait reply: " << endl;
thread wORq(quitHandler);
unique_lock<mutex> listLock(mtx);
while(!stopWaiting && !waitList){
getList.wait_for(listLock, chrono::milliseconds(10));
}
if(waitList || stopWaiting)
wORq.join();
if(stopWaiting) {
cout << "Interrupted by hand, didn't get the list" << endl;
break;
}
else if(waitList){
cout << "GET GET GET" << endl;
break;
}
}
} else {
cout << "Server ID " << svrId << " not found." << endl;
}
break;
}
case 5:{ // 获取客户端list
if(servers.empty()) {
cout << "No server connect" << endl;
break;
}
cout << "Choose a server to get the list of clients" << endl;
printSvrInfo(servers);
cout << "Input Server ID to request cilentlist or 0 to quit" << endl;
int svrId = getIn<int>(0,65535);
if(!svrId) break; // 0 = break
auto it = find_if(servers.begin(), servers.end(), [svrId](const serverInfo& server) {
return server.serverId == svrId; // 条件:根据输入的 serverId
});
// 检查是否找到
if (it != servers.end()) { // find success
string msg = "123456789";
int length;
// bodyType 3 = getclientlist
int requestId = it->requestId.getID();
string out = packStr(Type::REQUEST, 3, msg, to_string(STUID_CLIENT), length, requestId);
char *cMsg = new char[length+0];
StrToC(out, cMsg, length+0);
for(int i = 0;i < length+0; i++)
cout << (int)cMsg[i] << "|";
cout << endl;
waitList = false; // send 之前就 reset waitlist
stopWaiting = false; // send 之前就 reset stopwaiting
serverInfo &svr = *it;
sendC(svr, cMsg, length+0);
threads.emplace_back(ReceiveMsg, ref(svr));
{
cout << "Push id = " << requestId << endl;
Ids.push(requestId);
cout << "Wait reply: " << endl;
thread wORq(quitHandler);
unique_lock<mutex> listLock(mtx);
while(!stopWaiting && !waitList){
getList.wait_for(listLock, chrono::milliseconds(10));
}
if(waitList || stopWaiting)
wORq.join();
if(stopWaiting) {
cout << "Interrupted by hand, didn't get the list" << endl;
break;
}
else if(waitList){
cout << "GET GET GET" << endl;
// break;
cout << "Choose a client to send msg:" << endl;
int clientNum = getIn<int>(0, 65535);
string msg ;
cout << "Input your message to send:" << endl;
getline(cin, msg);
string result;
result += static_cast<uint8_t>(clientNum);
result += msg;
int length;
// bodyType 4 = choose client send msg
string out = packStr(Type::REQUEST, 4, result, to_string(STUID_CLIENT), length, it->requestId.getID());
StrToC(out, cMsg, length+0);
sendC(svr, cMsg, length+0);
threads.emplace_back(ReceiveMsg, ref(svr));
break;
}
}
} else {
cout << "Server ID " << svrId << " not found." << endl;
}
break;
}
case 6: // 退出
// 关闭所有服务器连接
if(!servers.empty()){
for (auto& it : servers) {
it.connect = false;
closesocket(it.socket);
}
}
// 发送退出信号给消费者
{
lock_guard<mutex> lock(mtx);
exitFlag = true;
}
res.notify_all(); // 通知消费者退出
// 结束消费者线程
if(consumerThread.joinable()) consumerThread.join();
// 等待所有线程完成
for (auto& t : threads) {
if(t.joinable())
t.join();
}
WSACleanup(); // 清理 Winsock
cout << " ***** \n";
cout << " * BYE * \n";
cout << " * O O * \n"; // 眼睛
cout << " * * * \n"; // 笑嘴
cout << " * \\_/ * \n";
cout << " ***** \n";
return 0;
break;
}
}
}