-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cpp
More file actions
880 lines (714 loc) · 31.1 KB
/
Copy pathServer.cpp
File metadata and controls
880 lines (714 loc) · 31.1 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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
// 自动链接 Windows Socket 2 库
#pragma comment(lib,"ws2_32.lib")
#define MaxClient 10
#define MaxBufSize 1024
#include <cstdio>
#include <iostream>
#include <string>
#include <WinSock2.h>
#include <ctime>
#include <vector>
#include "md5.h"
#include "Body.h"
#include "Packet.h"
#include <ws2tcpip.h>
#include <map>
#include <fstream>
#include <sstream>
#include <chrono>
#pragma comment(lib, "Ws2_32.lib")
using namespace std;
const int DEFAULT_PORT = 997; // 默认监听端口,学号后4位
const string studentID = to_string(4506);
using client = pair<SOCKET*, int>;
int ClIENTS_COUNT = 0;
vector<client> clientTcps; //已连接的用户列表
struct ClientInfo {
sockaddr_in clientAddr;
int number;
};
vector<ClientInfo> clientUdps;
bool useTCP = true;
SOCKET ListenSocket;
// 读取文件并将数据存储在 map 中
std::map<std::string, std::tuple<std::string, std::string>> readCityCodes(const std::string& filename) {
std::map<std::string, std::tuple<std::string, std::string>> cityCodes;
std::ifstream file(filename);
std::string line;
if (file.is_open()) {
while (std::getline(file, line)) {
std::istringstream iss(line);
std::string code, chineseName, englishName;
if (std::getline(iss, code, ',') && std::getline(iss, chineseName, ',') && std::getline(iss, englishName)) {
cityCodes[code] = std::make_tuple(chineseName, englishName);
}
}
file.close();
} else {
std::cerr << "can't open the file " << filename << std::endl;
}
return cityCodes;
}
std::string getCityName(const std::map<std::string, std::tuple<std::string, std::string>>& cityCodes, const std::string& code) {
auto it = cityCodes.find(code);
if (it != cityCodes.end()) {
std::string chineseName = std::get<0>(it->second);
std::string englishName = std::get<1>(it->second);
// 确保中文名称不超过10字节,并以'\0'结束
if (chineseName.size() > 9) {
chineseName = chineseName.substr(0, 9);
}
chineseName.resize(10, '\0');
// 确保英文名称不超过20字节,并以'\0'结束
if (englishName.size() > 19) {
englishName = englishName.substr(0, 19);
}
englishName.resize(20, '\0');
return chineseName + englishName;
} else {
// 返回默认的未知城市名称
std::string unknownChinese = "未知城市";
unknownChinese.resize(10, '\0');
std::string unknownEnglish = "Unknown City";
unknownEnglish.resize(20, '\0');
return unknownChinese + unknownEnglish;
}
}
// 读取文件并将数据存储在 map 中
std::map<std::tuple<std::string, int, int, int>, std::tuple<int, int, int, int, int>> readWeather(const std::string& filename) {
std::map<std::tuple<std::string, int, int, int>, std::tuple<int, int, int, int, int>> weatherData;
std::ifstream file(filename);
std::string line;
if (file.is_open()) {
while (std::getline(file, line)) {
std::istringstream iss(line);
std::string code, yearStr, monthStr, dayStr, temperatureStr, weatherFlagStr, windDirectionStr, windPowerStr, humidityStr;
char comma; // 用于跳过逗号
if (std::getline(iss, code, ',') && std::getline(iss, yearStr, ',') && std::getline(iss, monthStr, ',') && std::getline(iss, dayStr, ',') && std::getline(iss, temperatureStr, ',') && std::getline(iss, weatherFlagStr, ',') && std::getline(iss, windDirectionStr, ',') && std::getline(iss, windPowerStr, ',') && std::getline(iss, humidityStr)) {
int year = std::stoi(yearStr);
int month = std::stoi(monthStr);
int day = std::stoi(dayStr);
int temperature = std::stoi(temperatureStr);
int weatherFlag = std::stoi(weatherFlagStr);
int windDirection = std::stoi(windDirectionStr);
int windPower = std::stoi(windPowerStr);
int humidity = std::stoi(humidityStr);
auto key = std::make_tuple(code, year, month, day);
auto value = std::make_tuple(temperature, weatherFlag, windDirection, windPower, humidity);
weatherData[key] = value;
}
}
file.close();
} else {
std::cerr << "can't open the file " << filename << std::endl;
}
return weatherData;
}
// 获取特定区号和日期的天气信息
std::string getWeather(const std::map<std::tuple<std::string, int, int, int>, std::tuple<int, int, int, int, int>>& weatherData, const std::string& code, int year, int month, int day) {
auto key = std::make_tuple(code, year, month, day);
auto it = weatherData.find(key);
if (it != weatherData.end()) {
int temperature = std::get<0>(it->second);
int weatherFlag = std::get<1>(it->second);
int windDirection = std::get<2>(it->second);
int windPower = std::get<3>(it->second);
int humidity = std::get<4>(it->second);
cout << "found data" << temperature << weatherFlag << windDirection;
string result;
result += static_cast<int8_t>(temperature);
result += static_cast<uint8_t>(weatherFlag);
result += static_cast<uint8_t>(windDirection);
result += static_cast<uint8_t>(windPower);
result += static_cast<uint8_t>(humidity);
cout << "result: " << result << endl;
return result;
} else {
std::string notfind = "not find";
notfind = static_cast<int8_t>(0) + static_cast<uint8_t>(0) + static_cast<uint8_t>(0) + static_cast<uint8_t>(0) + static_cast<uint8_t>(0);
return notfind;
}
}
// tcp 专用
void getClientInfo(const client& cl, uint32_t& ip, uint16_t& port) {
sockaddr_in addr;
int addr_len = sizeof(addr);
if (getpeername(*cl.first, (sockaddr*)&addr, &addr_len) == 0) {
ip = ntohl(addr.sin_addr.s_addr); // 转换为主机字节序的 32 位整数 IP 地址
port = ntohs(addr.sin_port); // 转换为主机字节序的 16 位整数端口
// cout << "IP: " << ip << ", Port: " << port << endl;
// 将 IP 地址转换为点分十进制字符串格式
char ipStr[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(addr.sin_addr), ipStr, INET_ADDRSTRLEN);
// cout << "IP: " << ipStr << ", Port: " << port << endl;
} else {
cerr << "Failed to get peer name: " << WSAGetLastError() << endl;
}
}
int findClientInt(SOCKET* clientSocket) {
for (const auto& cl : clientTcps) {
if (cl.first == clientSocket) {
return cl.second;
}
}
// 如果没有找到,返回一个特殊值,例如 -1
return -1;
}
SOCKET* findClient(uint8_t clientID) {
for (const auto& cl : clientTcps) {
if (cl.second == clientID) {
return cl.first;
}
}
return nullptr;
}
void printWeatherData(const std::map<std::tuple<std::string, int, int, int>, std::tuple<int, int, int, int, int>>& weatherData) {
for (const auto& entry : weatherData) {
const auto& key = entry.first;
const auto& value = entry.second;
std::string code;
int year, month, day;
int tempHigh, tempLow, humidity, windSpeed, precipitation;
std::tie(code, year, month, day) = key;
std::tie(tempHigh, tempLow, humidity, windSpeed, precipitation) = value;
}
}
void HandleClientMessage(const char* RecvBuf,char* SendBuf,SOCKET* ClientSocket,sockaddr_in ClientAddr){ // for TCP present
cout << "Into HandleClientMessage" << endl;
Packet recPacket = Packet(RecvBuf,studentID);
cout << "Received Packet" << endl;
recPacket.printPacketInfo();
if(recPacket.getType()== Type::REQUEST){
if(recPacket.getBody().getType() == 1) // 获取城市名称
{
std::string filename = "city.txt";
std::map<std::string, std::tuple<std::string, std::string>> cityCodes = readCityCodes(filename);
vector<uint8_t> data = recPacket.getBody().getData();
string bodyString;
if (data.size()==4){
string code(data.begin(),data.end());
bodyString = getCityName(cityCodes, code);
}
else
{
bodyString = "Uncorrect code";
}
cout << "return: " << bodyString << endl;
vector<uint8_t> bodyVector(bodyString.begin(), bodyString.end());
string bodyContent = Body(recPacket.getBody().getSequence(),static_cast<uint8_t>(1),bodyVector).toString();
Packet sendPacket(Type::RESPONSE, bodyContent, studentID);
sendPacket.printPacketInfo();
// 打包
string sendstring = sendPacket.toString();
//strcpy(SendBuf, sentstring.c_str());
const char* ptr = sendstring.c_str();
for (int i = 0; i < sendstring.size(); i++) {
SendBuf[i] = ptr[i];
}
} else if (recPacket.getBody().getType() == 2){ // 获取天气信息
// 解包
vector<uint8_t> data = recPacket.getBody().getData();
// 提取区号
string code = std::string(data.begin(), data.begin() + 4);
// 提取年份
int year = std::stoi(std::string(data.begin() + 4, data.begin() + 8));
// 提取月份
int month = std::stoi(std::string(data.begin() + 8, data.begin() + 10));
// 提取日期
int day = std::stoi(std::string(data.begin() + 10, data.begin() + 12));
cout << "code: " << code << " year: " << year << " month: " << month << " day: " << day << endl;
// 读取天气数据
std::map<std::tuple<std::string, int, int, int>, std::tuple<int, int, int, int, int>> weatherData = readWeather("weather.txt");
printWeatherData(weatherData);
string bodyString = getWeather(weatherData, code, year, month, day);
vector<uint8_t> bodyVector(bodyString.begin(), bodyString.end());
string bodyContent = Body(recPacket.getBody().getSequence(),static_cast<uint8_t>(2),bodyVector).toString();
Packet sendPacket(Type::RESPONSE, bodyContent, studentID);
sendPacket.printPacketInfo();
// 打包
string sendstring = sendPacket.toString();
//strcpy(SendBuf, sentstring.c_str());
const char* ptr = sendstring.c_str();
for (int i = 0; i < sendstring.size(); i++) {
SendBuf[i] = ptr[i];
}
} else if(recPacket.getBody().getType() == 3){ // 获取客户端列表
uint8_t numOfOnlineClients;
if(useTCP) numOfOnlineClients = clientTcps.size();
else numOfOnlineClients = clientUdps.size();
string bodyString;
bodyString += numOfOnlineClients;
if(useTCP){
for (auto client : clientTcps) {
char byte0 = client.second;
bodyString += byte0;
uint32_t ip;
uint16_t port;
getClientInfo(client, ip, port);
char bytes[4];
bytes[0] = (ip >> 24) & 0xFF;
bytes[1] = (ip >> 16) & 0xFF;
bytes[2] = (ip >> 8) & 0xFF;
bytes[3] = ip & 0xFF;
// 将字节数组添加到 str
bodyString.append(bytes, 4);
char bytes2[2];
bytes2[0] = (port >> 8) & 0xFF;
bytes2[1] = port & 0xFF;
bodyString.append(bytes2, 2);
cout << "client: " << client.second << " ip: " << ip << " port: " << port << endl;
}
}else{ // useUDP
for(auto client : clientUdps) {
char byte0 = client.number;
bodyString += byte0;
uint32_t ip = ntohl((client.clientAddr).sin_addr.s_addr);
uint16_t port = ntohs(client.clientAddr.sin_port);
char bytes[4];
bytes[0] = (ip >> 24) & 0xFF;
bytes[1] = (ip >> 16) & 0xFF;
bytes[2] = (ip >> 8) & 0xFF;
bytes[3] = ip & 0xFF;
// 将字节数组添加到 str
bodyString.append(bytes, 4);
char bytes2[2];
bytes2[0] = (port >> 8) & 0xFF;
bytes2[1] = port & 0xFF;
bodyString.append(bytes2, 2);
}
}
// 打包
vector<uint8_t> bodyVector(bodyString.begin(), bodyString.end());
string bodyContent = Body(recPacket.getBody().getSequence(),static_cast<uint8_t>(3),bodyVector).toString();
Packet sendPacket(Type::RESPONSE, bodyContent, studentID);
sendPacket.printPacketInfo();
string test = "1234";
vector<uint8_t> test_bodyVector(test.begin(), test.end());
string test_bodyContent = Body(recPacket.getBody().getSequence(),static_cast<uint8_t>(3),test_bodyVector).toString();
Packet test_sendPacket(Type::RESPONSE, test_bodyContent, studentID);
// test_sendPacket.printPacketInfo();
string sendstring = sendPacket.toString();
const char* ptr = sendstring.c_str();
for (int i = 0; i < sendstring.size(); i++) {
SendBuf[i] = ptr[i];
}
} else if(recPacket.getBody().getType() == 4){ // 发送信息到指定端口
// 解包
vector<uint8_t> data = recPacket.getBody().getData();
// 提取目标客户端序号
uint8_t targetClient = data[0];
// 查询获得源编号
uint8_t sourceClient = findClientInt(ClientSocket);
// 提取消息内容
string message(data.begin() + 1, data.end());
// 先打包指示数据包
cout << "Pack Indication" << endl;
string bodyString;
bodyString += sourceClient;
bodyString += message;
vector<uint8_t> bodyVector(bodyString.begin(), bodyString.end());
string bodyContent = Body(recPacket.getBody().getSequence(),static_cast<uint8_t>(1),bodyVector).toString();
Packet sendPacket(Type::INDICATION, bodyContent, studentID);
cout << "Indication Packet" << endl;
sendPacket.printPacketInfo();
string indicationString = sendPacket.toString();
const char* ptr = indicationString.c_str();
char indicationBuf[MaxBufSize];
for (int i = 0; i < indicationString.size(); i++) {
indicationBuf[i] = ptr[i];
}
SOCKET* targetSocket = findClient(targetClient);
cout << "find target : " << *targetSocket << endl;
int success = send(*targetSocket, indicationBuf, sizeof(indicationBuf), 0);
cout << "send indication success: " << success << endl;
if (success == SOCKET_ERROR) {
success = 0;
}else{
success = 1;
}
// 打包响应数据包
cout << "Pack Response" << endl;
bodyString = "";
bodyString += sourceClient + static_cast<uint8_t>(success);
vector<uint8_t> bodyVector2(bodyString.begin(), bodyString.end());
bodyContent = Body(recPacket.getBody().getSequence(),static_cast<uint8_t>(4),bodyVector2).toString();
Packet sendPacket2(Type::RESPONSE, bodyContent, studentID);
cout << "Response Packet" << endl;
sendPacket2.printPacketInfo();
string sendstring = sendPacket2.toString();
const char* ptr2 = sendstring.c_str();
for (int i = 0; i < sendstring.size(); i++) {
SendBuf[i] = ptr2[i];
}
} else if (recPacket.getBody().getType()==5){ // 建立连接udp
if(useTCP) return;
ClientInfo newclient;
newclient.clientAddr = ClientAddr;
newclient.number = ClIENTS_COUNT++;
clientUdps.push_back(newclient);
// boardcast newclients
string bodyString;
bodyString += static_cast<uint8_t>(newclient.number);
uint32_t ip = ntohl(ClientAddr.sin_addr.s_addr);
uint16_t port = ntohs(ClientAddr.sin_port);
char bytes[4];
bytes[0] = (ip >> 24) & 0xFF;
bytes[1] = (ip >> 16) & 0xFF;
bytes[2] = (ip >> 8) & 0xFF;
bytes[3] = ip & 0xFF;
bodyString.append(bytes, 4);
cout << "ip : " << ip << endl;
char bytes2[2];
bytes2[0] = (port >> 8) & 0xFF;
bytes2[1] = port & 0xFF;
cout << "port : " << port << endl;
bodyString.append(bytes2, 2);
// 打包
vector<uint8_t> bodyVector(bodyString.begin(), bodyString.end());
string bodyContent = Body(recPacket.getBody().getSequence(),static_cast<uint8_t>(2),bodyVector).toString();
Packet sendPacket(Type::INDICATION, bodyContent, studentID);
sendPacket.printPacketInfo();
char BoardBuf[MaxBufSize];
string sendstring = sendPacket.toString();
const char* ptr = sendstring.c_str();
for (int i = 0; i < sendstring.size(); i++) {
BoardBuf[i] = ptr[i];
}
for(auto client : clientUdps){
int clientAddrSize = sizeof(client.clientAddr);
sendto(ListenSocket, SendBuf,MaxBufSize, 0, (sockaddr*)&client.clientAddr, clientAddrSize);
}
} else if (recPacket.getBody().getType() == 6){ // 释放连接udp
if (useTCP) return;
uint32_t ip;
uint16_t port;
uint8_t clientNum;
for (auto iter = clientUdps.begin(); iter != clientUdps.end(); iter++) {
if ((*iter).clientAddr.sin_addr.s_addr == ClientAddr.sin_addr.s_addr && (*iter).clientAddr.sin_port == ClientAddr.sin_port) {
clientNum = (*iter).number;
ip = (*iter).clientAddr.sin_addr.s_addr;
port = (*iter).clientAddr.sin_port;
iter = clientUdps.erase(iter);
break;
}
}
// boardcast deleteclients
string bodyString;
bodyString += static_cast<uint8_t>(clientNum);
char bytes[4];
bytes[0] = (ip >> 24) & 0xFF;
bytes[1] = (ip >> 16) & 0xFF;
bytes[2] = (ip >> 8) & 0xFF;
bytes[3] = ip & 0xFF;
bodyString.append(bytes, 4);
char bytes2[2];
bytes2[0] = (port >> 8) & 0xFF;
bytes2[1] = port & 0xFF;
bodyString.append(bytes2, 2);
// 打包
vector<uint8_t> bodyVector(bodyString.begin(), bodyString.end());
string bodyContent = Body(0,static_cast<uint8_t>(3),bodyVector).toString();
Packet sendPacket(Type::INDICATION, bodyContent, studentID);
sendPacket.printPacketInfo();
char BoardBuf[MaxBufSize];
string sendstring = sendPacket.toString();
const char* ptr = sendstring.c_str();
for (int i = 0; i < sendstring.size(); i++) {
BoardBuf[i] = ptr[i];
}
for(auto client : clientUdps){
int clientAddrSize = sizeof(client.clientAddr);
sendto(ListenSocket, SendBuf,MaxBufSize, 0, (sockaddr*)&client.clientAddr, clientAddrSize);
}
} else {
cout << "Invalid type" << endl;
}
}
}
// Windows API 线程函数
DWORD WINAPI ServerThreadTCP(LPVOID lpParameter)
{
SOCKET* ClientSocket = (SOCKET*)lpParameter;
int receByt = 0;
char RecvBuf[MaxBufSize];
char SendBuf[MaxBufSize];
while(1)
{
receByt = recv(*ClientSocket, RecvBuf, sizeof(RecvBuf), 0);
if(receByt > 0)
{
cout << "Receive message from client " << *ClientSocket << endl;
RecvBuf[receByt] = '\0'; // 确保字符串以 null 结尾
cout << "Message content: " << RecvBuf << endl;
cout << "Ready to into Handle" << endl;
sockaddr_in NullAddr;
HandleClientMessage(RecvBuf,SendBuf,ClientSocket,NullAddr);
cout << "Handle finished" << endl;
cout << "size "<<sizeof(SendBuf) << endl;
send(*ClientSocket, SendBuf, sizeof(SendBuf), 0);
} else {
// 被迫断联
cout << "[system] Client(" << *ClientSocket << ") has been disconnected" << endl;
uint8_t clientNum;
// 从列表中删除 Clients
for (auto iter = clientTcps.begin(); iter != clientTcps.end(); iter++) {
if ((*iter).first == ClientSocket) {
clientNum = (*iter).second;
iter = clientTcps.erase(iter);
break;
}
}
// boardcast deleteclients
string bodyString;
bodyString += static_cast<uint8_t>(clientNum);
uint32_t ip;
uint16_t port;
getClientInfo(pair<SOCKET*,int>(ClientSocket,0), ip, port);
char bytes[4];
bytes[0] = (ip >> 24) & 0xFF;
bytes[1] = (ip >> 16) & 0xFF;
bytes[2] = (ip >> 8) & 0xFF;
bytes[3] = ip & 0xFF;
bodyString.append(bytes, 4);
char bytes2[2];
bytes2[0] = (port >> 8) & 0xFF;
bytes2[1] = port & 0xFF;
bodyString.append(bytes2, 2);
// 打包
vector<uint8_t> bodyVector(bodyString.begin(), bodyString.end());
string bodyContent = Body(0,static_cast<uint8_t>(3),bodyVector).toString();
Packet sendPacket(Type::INDICATION, bodyContent, studentID);
sendPacket.printPacketInfo();
char BoardBuf[MaxBufSize];
string sendstring = sendPacket.toString();
const char* ptr = sendstring.c_str();
for (int i = 0; i < sendstring.size(); i++) {
BoardBuf[i] = ptr[i];
}
for(auto client : clientTcps){
send(*(client.first),BoardBuf,sizeof(BoardBuf),0);
}
break;
}
}
closesocket(*ClientSocket);
free(ClientSocket);
return 0;
}
string getIndication(){
string bodystring;
char type;
do{
cout << "Please input the type of the indication: (1 for earthquake, 2 for typhoon) ";
cin >> type;
}while(type != '1' && type != '2');
bodystring += type;
int longitude_interger, latitude_interger;
int longitude_decimal , latitude_decimal;
do{
cout << "Please input the longitude integer part: ";
cin >> longitude_interger;
}while(longitude_interger < -180 || longitude_interger > 180);
do{
cout << "Please input the longitude decimal part: ";
cin >> longitude_decimal;
}while(longitude_decimal < 0 || longitude_decimal > 99);
do{
cout << "Please input the latitude integer part: ";
cin >> latitude_interger;
}while(latitude_interger < -90 || latitude_interger > 90);
do{
cout << "Please input the latitude decimal part: ";
cin >> latitude_decimal;
}while(latitude_decimal < 0 || latitude_decimal > 99);
bodystring += static_cast<int8_t>(longitude_interger);
bodystring += static_cast<uint8_t>(longitude_decimal);
bodystring += static_cast<int8_t>(latitude_interger);
bodystring += static_cast<uint8_t>(latitude_decimal);
int warningLevel;
do{
cout << "Please input the warning type: ";
cin >> warningLevel;
}while(warningLevel < 0 || warningLevel > 255);
bodystring += static_cast<uint8_t>(warningLevel);
string month,day,hour,minute;
do{
cout << "Please input the month: ";
cin >> month;
}while(month.length() != 2 || stoi(month) < 1 || stoi(month) > 12);
do{
cout << "Please input the day: ";
cin >> day;
}while(day.length() != 2 || stoi(day) < 1 || stoi(day) > 31);
do{
cout << "Please input the hour: ";
cin >> hour;
}while(hour.length() != 2 || stoi(hour) < 0 || stoi(hour) > 23);
do{
cout << "Please input the minute: ";
cin >> minute;
}while (minute.length() != 2 || stoi(minute) < 0 || stoi(minute) > 59);
bodystring = bodystring + month + day + hour + minute;
string location;
do{
cout << "Please input the location: ";
cin >> location;
}while(location.length() >10);
bodystring += location;
return bodystring;
}
DWORD WINAPI BoardCast(LPVOID lpParameter){
vector<uint8_t> defaultbodyVector = {
1, // 预警类型
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', // 经度 (123456.789001)
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '2', // 纬度 (123456.789002)
5, // 级别
'2', '0', '2', '4', '1', '0', '2', '1', '2', '3', // 时间
'L', 'o', 'c', 'a', 't', 'i', 'o', 'n', '\0', '\0' // 地点
};
while(1){
Sleep(300000);
string bodyString = getIndication();
vector<uint8_t> bodyVector(bodyString.begin(), bodyString.end());
string bodyContent = Body(0,static_cast<uint8_t>(4),bodyVector).toString();
Packet sendPacket(Type::INDICATION, bodyContent, studentID);
sendPacket.printPacketInfo();
char SendBuf[MaxBufSize];
string sendstring = sendPacket.toString();
const char* ptr = sendstring.c_str();
for (int i = 0; i < sendstring.size(); i++) {
SendBuf[i] = ptr[i];
}
if(useTCP){
if(clientTcps.size()>0){
for(client client : clientTcps){
send(*(client.first),SendBuf,sizeof(SendBuf),0);
}
}
}else{
if(clientUdps.size()>0){
for(ClientInfo client : clientUdps){
int clientAddrSize = sizeof(client.clientAddr);
sendto(ListenSocket, SendBuf,MaxBufSize, 0, (sockaddr*)&client.clientAddr, clientAddrSize);
}
}
}
}
}
int main(int argc, char* argv[])
{
// 初始化 Windows Socket
WSAData wsd;
WSAStartup(MAKEWORD(2, 2), &wsd);
// SOCKET ListenSocket = socket(AF_INET, SOCK_STREAM, 0);
// 定义并初始化监听端口
SOCKADDR_IN ListenAddr;
ListenAddr.sin_family = AF_INET;
ListenAddr.sin_addr.S_un.S_addr = INADDR_ANY; // 表示填入本机ip
ListenAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
// 解析命令行参数以获取端口号
int PORT = DEFAULT_PORT; // 使用默认端口
if (argc > 1) {
PORT = atoi(argv[1]); // 将第一个参数转换为整数
if (PORT <= 0 || PORT > 65535) {
cout << "[error] Invalid port number. Using default port " << DEFAULT_PORT << "." << endl;
PORT = DEFAULT_PORT;
}
}
if (argc > 2) {
string protocol = argv[2];
if (protocol == "UDP" || protocol == "udp") {
useTCP = false;
}
}
ListenAddr.sin_port = htons(PORT);
// 创建套接字
// SOCKET ListenSocket;
if (useTCP) {
ListenSocket = socket(AF_INET, SOCK_STREAM, 0);
} else {
ListenSocket = socket(AF_INET, SOCK_DGRAM, 0);
}
// 绑定套接字
int success = bind(ListenSocket, (LPSOCKADDR)&ListenAddr, sizeof(ListenAddr));
if(success == SOCKET_ERROR) {
cout << "[initialize] Bind failed!" << endl;
return -1;
} else {
cout << "[initialize] Bind successfully to port " << PORT << "!" << endl;
}
DWORD threadID;
//CreateThread(NULL, 0, &BoardCast, NULL, 0, NULL);
if(useTCP) {
// 开始监听
listen(ListenSocket, MaxClient);
cout << "[initialize] Waiting for clients ..." << endl;
while(1)
{
// 创建服务进程
SOCKET* ClientSocket = new SOCKET;
*ClientSocket = accept(ListenSocket, 0, 0);
cout << "[new client] " << *ClientSocket << " connected!" << endl;
clientTcps.push_back(pair<SOCKET*, int>(ClientSocket, ClIENTS_COUNT++));
// boardcast newclients
string bodyString;
bodyString += static_cast<uint8_t>(ClIENTS_COUNT-1);
uint32_t ip;
uint16_t port;
getClientInfo(clientTcps.back(), ip, port);
char bytes[4];
bytes[0] = (ip >> 24) & 0xFF;
bytes[1] = (ip >> 16) & 0xFF;
bytes[2] = (ip >> 8) & 0xFF;
bytes[3] = ip & 0xFF;
bodyString.append(bytes, 4);
char bytes2[2];
bytes2[0] = (port >> 8) & 0xFF;
bytes2[1] = port & 0xFF;
bodyString.append(bytes2, 2);
// 打包
vector<uint8_t> bodyVector(bodyString.begin(), bodyString.end());
string bodyContent = Body(0,static_cast<uint8_t>(2),bodyVector).toString();
Packet sendPacket(Type::INDICATION, bodyContent, studentID);
sendPacket.printPacketInfo();
char SendBuf[MaxBufSize];
string sendstring = sendPacket.toString();
const char* ptr = sendstring.c_str();
for (int i = 0; i < sendstring.size(); i++) {
SendBuf[i] = ptr[i];
}
for(auto client : clientTcps){
send(*(client.first),SendBuf,sizeof(SendBuf),0);
}
// 启动新进程处理客户端请求
DWORD threadID;
CreateThread(NULL, 0, &ServerThreadTCP, ClientSocket, 0, NULL);
}
} else {
// UDP 服务器
cout << "[initialize] UDP server started on port " << PORT << endl;
// 用于接收数据的缓冲区和客户端地址结构
char RecvBuf[MaxBufSize];
char SendBuf[MaxBufSize];
sockaddr_in clientAddr;
int clientAddrSize = sizeof(clientAddr);
// 持续接收来自客户端的消息
while (true) {
// 接收数据
int receivedBytes = recvfrom(ListenSocket, RecvBuf, MaxBufSize, 0, (sockaddr*)&clientAddr, &clientAddrSize);
if (receivedBytes > 0) {
RecvBuf[receivedBytes] = '\0'; // 使接收到的字符串以 null 结尾
std::cout << "Received message: " << RecvBuf << std::endl;
HandleClientMessage(RecvBuf,SendBuf,nullptr,clientAddr);
Packet recPacket = Packet(RecvBuf,studentID);
if(recPacket.getBody().getType() != 5){
cout << "send back" << endl;
sendto(ListenSocket, SendBuf, MaxBufSize, 0, (sockaddr*)&clientAddr, clientAddrSize);
}
}
}
}
closesocket(ListenSocket);
WSACleanup();
return 0;
}