C++ 网络编程

outlook:

[TOC]

数据转换

C++: byte和int的相互转化_PuttyTree的博客-CSDN博客_c++ byte转int

C++ sockt

recv

1
2
3
const int bufLen = 256;
char buffer[bufLen];
int resultLen = recv(sclient, buffer, bufLen, 0);

FIX-01 “undefined reference to __imp_WSAStartup’”

1
2
3
4
<!--# VS task.xml配置修改:-->
"args": [
"C:/Program Files (x86)/Windows Kits/10/Lib/10.0.19041.0/um/x64/WS2_32.Lib",
]

Windows 网络编程

阻塞模式开发(执行I/O操作时,线程被阻塞调用)

非阻塞模式开发(执行I/O操作时,立即返回,但是要处理返回错误的问题)

套接字Select模型(常见的I/O模型)

UDP (Send/Recv Text)

Sever

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
#include <iostream>
#include <winsock2.h>
#include <string>
#include <fstream>
#include "windows.h"
#include "stdio.h"

#pragma comment(lib, "ws2_32.lib")

using namespace std;

int main()
{
WSADATA wsd;
SOCKET s;

// init
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
{
cout << "WSA Start UP faild" << endl;
return 1;
}

// socket creat
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s == INVALID_SOCKET)
{
cout << "socket() failed " << WSAGetLastError() << endl;
WSACleanup();
return 1;
}
// socket bind
SOCKADDR_IN servAddr;
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons((short) 5000); // PORT
servAddr.sin_addr.s_addr = htonl(INADDR_ANY); // IP
if (bind(s, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
{
cout << "bind() failed " << WSAGetLastError() << endl;
closesocket(s);
WSACleanup();
return 1;
}

// recv
int BUF_SIZE = 64;
char buf[BUF_SIZE];
// recv
SOCKADDR_IN clientAddr;
int nClientLen = sizeof(clientAddr);
if (recvfrom(s, buf, BUF_SIZE, 0, (SOCKADDR*)&clientAddr, &nClientLen) == SOCKET_ERROR)
{
cout << "recefrom() failed " << WSAGetLastError() << endl;
closesocket(s);
WSACleanup();
return 1;
}
cout << clientAddr.sin_addr.s_addr << endl;
cout << "recv : " << buf << endl;


}

client

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
#include <iostream>
#include <winsock2.h>
#include <string>
#include <fstream>
#include "windows.h"
#include "stdio.h"

using namespace std;

string constructBody(string args[2], string file[2]);
string readFile(string fileName);

#define PORT 5000
#define IP "127.0.0.1"
#define HOST "localhost"
#define RECEIVER "receive_data"
#define COMPNAME "compname"
#define PROGRAM "program"
#define FILENAME "file"
#define BOUNDARY "--------FVIAlihiu"
#define DUMMY_DATA "-todo"
#define DUMMY_FILE "dummy.txt"

/// @brief Windows SOcket 网络开发
/// ref : http://9v.lt/blog/sending-multipart-post-requests-c/
/// @return
int main()
{
SOCKET dataSock;
WSADATA wasData;
int error = WSAStartup(0x0202, &wasData);
if (error != 0)
{
WSACleanup();
exit(1);
}


// dataSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
dataSock = socket(AF_INET, SOCK_DGRAM, 0);
if (dataSock == INVALID_SOCKET)
{
exit(1);
}

SOCKADDR_IN target;
target.sin_family = AF_INET;
target.sin_port = htons(PORT);
target.sin_addr.s_addr = inet_addr(IP);

connect(dataSock, (SOCKADDR*)&target, sizeof(target));

string programNames[1][2] = {{"KULVERTOP", "Chrome"}};
string file[2] = {FILENAME, "Default.txt"};

int a = sizeof( programNames)/sizeof( programNames[0]);
for (int i = 0; i < a; i++)
{
cout << "Send data for " << programNames[i][1] << endl;
string body = constructBody(programNames[i], file);
char header[1024];
// cout << header
sprintf(header, "POST %s HTTP1.1 \r\n"
"Host: %s\r\n"
"Content-Length: %d\r\n"
"Content-Type: multipart/from-data; boundary=%s\r\n"
"Accept-Charset: utf-8\r\n\r\n",
RECEIVER, IP, strlen(body.c_str()), BOUNDARY);

cout << header << endl;
// int p = send(dataSock, header, strlen(header), 0);
// int k = send(dataSock, body.c_str(), strlen(body.c_str()), 0);
char buf[64] = "My UDP";
// int t = send(dataSock, buf, strlen(buf), 0);
int t = send(dataSock, buf, 64, 0);

}

closesocket(dataSock);
WSACleanup();
}

string readFile(string file)
{
string fileContents;
ifstream tmp(file.c_str());
getline(tmp, fileContents);
tmp.close();

return fileContents;
}

string constructBody(string args[2], string file[2])
{
string body;
string CRLF = "\r\n";

// first we add the args
body.append("--" + string(BOUNDARY) + CRLF);
body.append("Content-Disposition: from-data; name=\"" + string(COMPNAME) + "\"" + CRLF);
body.append(CRLF);
body.append(args[0] + CRLF);
body.append("--" + string(BOUNDARY) + CRLF);
body.append("Content-Disposition: from-data; name=\"" + string(PROGRAM) + "\"" + CRLF);
body.append(CRLF);
body.append(args[1] + CRLF);

// now we add the file
body.append("--" + string(BOUNDARY) + CRLF);
body.append("Content-Disposition: from-data; name=\"" + string(FILENAME) + "\"; filename=\"" + string(DUMMY_FILE) + "\"" + CRLF);
body.append("Content-Type:text/plain" + CRLF);
body.append("--" + string(BOUNDARY) + "--" + CRLF);
body.append(CRLF);

return body;
}

demo::Socket文件传输

Client Server
Method-1 发送4字节(的文件长度)+文件的内容String 接受对应格式的文件
Method-2

LINUX网络编程

基础知识

c++网络编程基础知识总结_你最特别17的博客-CSDN博客_网络口c++

EPOLLIN , EPOLLOUT , EPOLLPRI, EPOLLERR 和 EPOLLHUP事件

poll()函数ref

1
2
3
4
5
6
7
8
9
10
POLLIN:                有普通数据或者优先数据可读
POLLRDNORM: 有普通数据可读
POLLRDBAND: 有优先数据可读
POLLPRI: 有紧急数据可读
POLLOUT: 有普通数据可写
POLLWRNORM: 有普通数据可写
POLLWRBAND: 有紧急数据可写
POLLERR: 有错误发生
POLLHUP: 有描述符挂起事件发生
POLLNVAL: 描述符非法

Client

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
//client Linux 
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>

using namespace std;

int main()
{
cout << "this is client" <<endl;
int client = socket(AF_INET, SOCK_STREAM, 0);
if(client == -1)
{
cout << " socket err " <<endl;
return 0;
}
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(7637);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

if(connect(client, (struct sockaddr_in*) &serverAddr, sizeof(serverAddr)) < 0)
{
cout << "connect err" <<endl;
return 0;
}
cout << "connect ...." <<endl;
char data[255];
char buf[255];
while (true)
{
cin >> data;
send(client, data, strlen(data), 0);
if(strcmp(data, "exit") == 0 || strcmp(data, "EXIT") == 0)
{
cout << "client disconnect ..." <<endl;
break;
}
memset(buf, 0 ,sizeof(buf));
int len = recv(client, buf, sizeof(buf), 0);
buf[len] = '\0';

cout << buf << endl;
}
close(client);
return 0;
}

Server

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
//server linux 
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>

using namespace std;


int main()
{
cout << "this is server" <<endl;
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd == -1)
{
cout << "socker err " <<endl;
return 0;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(7637);
addr.sin_addr.s_addr = INADDR_ANY;

if(bind(listenfd, (struct sockaddr*) &addr,sizeof(addr)) == -1)
{
cout << "bind err" <<endl;
return 0;
}
if(listen(listenfd , 5) == -1)
{
cout <<"listen err" <<endl;
}

int conn;
char clientIP[INET_ADDRSTRLEN] = "";
struct sockaddr_in clientAddr;
socklen_t clinetAddrLen = sizeof(clientAddr);
while (true)
{
cout << "listen ...." <<endl;
conn = accept(listenfd, (struct sockaddr*)&clientAddr, &clinetAddrLen);
if(conn < 0)
{
cout <<"conn accept err " <<endl;
continue;
}

inet_ntop(AF_INET, &clientAddr.sin_addr, clientIP, INET_ADDRSTRLEN);
cout << " connect " << clientIP << ":" << ntohs(clientAddr.sin_port) << endl;

char buf[255];
while (true)
{
memset(buf, 0 , sizeof(buf));
int len = recv(conn, buf, sizeof(buf), 0);
buf[len] = '\0';
if(strcmp(buf,"exit") == 0 || strcmp(buf,"EXIT") == 0)
{
cout << "disconnect " << clientIP << ":" <<ntohs(clientAddr.sin_port) << endl;
break;
}
cout << buf << endl;
send(conn, buf, len,0)
}
close(conn);
}
close(listenfd);
return 0;

}

C++ socket demo_andyleung520的博客-CSDN博客_c++ socket demo

C++ Http

C++ 发送HTTP请求_BUG·搬运工的博客-CSDN博客_c++ http请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "HTTPRequest.hpp" //相关源码在文章末尾

...

//注意:URI地址必须以 http:// 开头,否则不符合头文件校验规则
string uri = "http://en.xxx.com/api-ctl/client/health/";
string method = "POST";
string arguments = string_To_UTF8((char*)encryptStr.c_str());
auto protocol = http::InternetProtocol::V4;
http::Request req{ uri, protocol };

json responseJson;
try {
const auto response = req.send(method, arguments, {
{"Content-Type", "application/json"},
{"User-Agent", "runscope/0.1"},
{"Accept", "*/*"}
}, std::chrono::seconds(2));
responseJson = json::parse(string{ response.body.begin(), response.body.end() });
}
catch (exception& e) {
//捕获请求失败异常,处理逻辑自行添加
}

HTTPRequest.hpp

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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
//  HTTPRequest

#ifndef HTTPREQUEST_HPP
#define HTTPREQUEST_HPP

#include <cctype>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <algorithm>
#include <array>
#include <chrono>
#include <functional>
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
#include <system_error>
#include <type_traits>
#include <vector>

#if defined(_WIN32) || defined(__CYGWIN__)
# pragma push_macro("WIN32_LEAN_AND_MEAN")
# pragma push_macro("NOMINMAX")
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif // WIN32_LEAN_AND_MEAN
# ifndef NOMINMAX
# define NOMINMAX
# endif // NOMINMAX
# include <winsock2.h>
# if _WIN32_WINNT < _WIN32_WINNT_WINXP
extern "C" char *_strdup(const char *strSource);
# define strdup _strdup
# include <wspiapi.h>
# endif // _WIN32_WINNT < _WIN32_WINNT_WINXP
# include <ws2tcpip.h>
# pragma pop_macro("WIN32_LEAN_AND_MEAN")
# pragma pop_macro("NOMINMAX")
#else
# include <errno.h>
# include <fcntl.h>
# include <netinet/in.h>
# include <netdb.h>
# include <sys/select.h>
# include <sys/socket.h>
# include <sys/types.h>
# include <unistd.h>
#endif // defined(_WIN32) || defined(__CYGWIN__)

namespace http
{
class RequestError final: public std::logic_error
{
public:
using std::logic_error::logic_error;
};

class ResponseError final: public std::runtime_error
{
public:
using std::runtime_error::runtime_error;
};

enum class InternetProtocol: std::uint8_t
{
V4,
V6
};

struct Uri final
{
std::string scheme;
std::string user;
std::string password;
std::string host;
std::string port;
std::string path;
std::string query;
std::string fragment;
};

struct HttpVersion final
{
uint16_t major;
uint16_t minor;
};

struct Status final
{
// RFC 7231, 6. Response Status Codes
enum Code: std::uint16_t
{
Continue = 100,
SwitchingProtocol = 101,
Processing = 102,
EarlyHints = 103,

Ok = 200,
Created = 201,
Accepted = 202,
NonAuthoritativeInformation = 203,
NoContent = 204,
ResetContent = 205,
PartialContent = 206,
MultiStatus = 207,
AlreadyReported = 208,
ImUsed = 226,

MultipleChoice = 300,
MovedPermanently = 301,
Found = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
TemporaryRedirect = 307,
PermanentRedirect = 308,

BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
PayloadTooLarge = 413,
UriTooLong = 414,
UnsupportedMediaType = 415,
RangeNotSatisfiable = 416,
ExpectationFailed = 417,
MisdirectedRequest = 421,
UnprocessableEntity = 422,
Locked = 423,
FailedDependency = 424,
TooEarly = 425,
UpgradeRequired = 426,
PreconditionRequired = 428,
TooManyRequests = 429,
RequestHeaderFieldsTooLarge = 431,
UnavailableForLegalReasons = 451,

InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
HttpVersionNotSupported = 505,
VariantAlsoNegotiates = 506,
InsufficientStorage = 507,
LoopDetected = 508,
NotExtended = 510,
NetworkAuthenticationRequired = 511
};

HttpVersion httpVersion;
std::uint16_t code;
std::string reason;
};

using HeaderField = std::pair<std::string, std::string>;
using HeaderFields = std::vector<HeaderField>;

struct Response final
{
Status status;
HeaderFields headerFields;
std::vector<std::uint8_t> body;
};

inline namespace detail
{
#if defined(_WIN32) || defined(__CYGWIN__)
class WinSock final
{
public:
WinSock()
{
WSADATA wsaData;
const auto error = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (error != 0)
throw std::system_error{error, std::system_category(), "WSAStartup failed"};

if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
WSACleanup();
throw std::runtime_error{"Invalid WinSock version"};
}

started = true;
}

~WinSock()
{
if (started) WSACleanup();
}

WinSock(WinSock&& other) noexcept:
started{other.started}
{
other.started = false;
}

WinSock& operator=(WinSock&& other) noexcept
{
if (&other == this) return *this;
if (started) WSACleanup();
started = other.started;
other.started = false;
return *this;
}

private:
bool started = false;
};
#endif // defined(_WIN32) || defined(__CYGWIN__)

inline int getLastError() noexcept
{
#if defined(_WIN32) || defined(__CYGWIN__)
return WSAGetLastError();
#else
return errno;
#endif // defined(_WIN32) || defined(__CYGWIN__)
}

constexpr int getAddressFamily(const InternetProtocol internetProtocol)
{
return (internetProtocol == InternetProtocol::V4) ? AF_INET :
(internetProtocol == InternetProtocol::V6) ? AF_INET6 :
throw RequestError{"Unsupported protocol"};
}

class Socket final
{
public:
#if defined(_WIN32) || defined(__CYGWIN__)
using Type = SOCKET;
static constexpr Type invalid = INVALID_SOCKET;
#else
using Type = int;
static constexpr Type invalid = -1;
#endif // defined(_WIN32) || defined(__CYGWIN__)

explicit Socket(const InternetProtocol internetProtocol):
endpoint{socket(getAddressFamily(internetProtocol), SOCK_STREAM, IPPROTO_TCP)}
{
if (endpoint == invalid)
throw std::system_error{getLastError(), std::system_category(), "Failed to create socket"};

#if defined(_WIN32) || defined(__CYGWIN__)
ULONG mode = 1;
if (ioctlsocket(endpoint, FIONBIO, &mode) != 0)
{
close();
throw std::system_error{WSAGetLastError(), std::system_category(), "Failed to get socket flags"};
}
#else
const auto flags = fcntl(endpoint, F_GETFL);
if (flags == -1)
{
close();
throw std::system_error{errno, std::system_category(), "Failed to get socket flags"};
}

if (fcntl(endpoint, F_SETFL, flags | O_NONBLOCK) == -1)
{
close();
throw std::system_error{errno, std::system_category(), "Failed to set socket flags"};
}
#endif // defined(_WIN32) || defined(__CYGWIN__)

#ifdef __APPLE__
const int value = 1;
if (setsockopt(endpoint, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value)) == -1)
{
close();
throw std::system_error{errno, std::system_category(), "Failed to set socket option"};
}
#endif // __APPLE__
}

~Socket()
{
if (endpoint != invalid) close();
}

Socket(Socket&& other) noexcept:
endpoint{other.endpoint}
{
other.endpoint = invalid;
}

Socket& operator=(Socket&& other) noexcept
{
if (&other == this) return *this;
if (endpoint != invalid) close();
endpoint = other.endpoint;
other.endpoint = invalid;
return *this;
}

void connect(const struct sockaddr* address, const socklen_t addressSize, const std::int64_t timeout)
{
#if defined(_WIN32) || defined(__CYGWIN__)
auto result = ::connect(endpoint, address, addressSize);
while (result == -1 && WSAGetLastError() == WSAEINTR)
result = ::connect(endpoint, address, addressSize);

if (result == -1)
{
if (WSAGetLastError() == WSAEWOULDBLOCK)
{
select(SelectType::write, timeout);

char socketErrorPointer[sizeof(int)];
socklen_t optionLength = sizeof(socketErrorPointer);
if (getsockopt(endpoint, SOL_SOCKET, SO_ERROR, socketErrorPointer, &optionLength) == -1)
throw std::system_error{WSAGetLastError(), std::system_category(), "Failed to get socket option"};

int socketError;
std::memcpy(&socketError, socketErrorPointer, sizeof(socketErrorPointer));

if (socketError != 0)
throw std::system_error{socketError, std::system_category(), "Failed to connect"};
}
else
throw std::system_error{WSAGetLastError(), std::system_category(), "Failed to connect"};
}
#else
auto result = ::connect(endpoint, address, addressSize);
while (result == -1 && errno == EINTR)
result = ::connect(endpoint, address, addressSize);

if (result == -1)
{
if (errno == EINPROGRESS)
{
select(SelectType::write, timeout);

int socketError;
socklen_t optionLength = sizeof(socketError);
if (getsockopt(endpoint, SOL_SOCKET, SO_ERROR, &socketError, &optionLength) == -1)
throw std::system_error{errno, std::system_category(), "Failed to get socket option"};

if (socketError != 0)
throw std::system_error{socketError, std::system_category(), "Failed to connect"};
}
else
throw std::system_error{errno, std::system_category(), "Failed to connect"};
}
#endif // defined(_WIN32) || defined(__CYGWIN__)
}

std::size_t send(const void* buffer, const std::size_t length, const std::int64_t timeout)
{
select(SelectType::write, timeout);
#if defined(_WIN32) || defined(__CYGWIN__)
auto result = ::send(endpoint, reinterpret_cast<const char*>(buffer),
static_cast<int>(length), 0);

while (result == -1 && WSAGetLastError() == WSAEINTR)
result = ::send(endpoint, reinterpret_cast<const char*>(buffer),
static_cast<int>(length), 0);

if (result == -1)
throw std::system_error{WSAGetLastError(), std::system_category(), "Failed to send data"};
#else
auto result = ::send(endpoint, reinterpret_cast<const char*>(buffer),
length, noSignal);

while (result == -1 && errno == EINTR)
result = ::send(endpoint, reinterpret_cast<const char*>(buffer),
length, noSignal);

if (result == -1)
throw std::system_error{errno, std::system_category(), "Failed to send data"};
#endif // defined(_WIN32) || defined(__CYGWIN__)
return static_cast<std::size_t>(result);
}

std::size_t recv(void* buffer, const std::size_t length, const std::int64_t timeout)
{
select(SelectType::read, timeout);
#if defined(_WIN32) || defined(__CYGWIN__)
auto result = ::recv(endpoint, reinterpret_cast<char*>(buffer),
static_cast<int>(length), 0);

while (result == -1 && WSAGetLastError() == WSAEINTR)
result = ::recv(endpoint, reinterpret_cast<char*>(buffer),
static_cast<int>(length), 0);

if (result == -1)
throw std::system_error{WSAGetLastError(), std::system_category(), "Failed to read data"};
#else
auto result = ::recv(endpoint, reinterpret_cast<char*>(buffer),
length, noSignal);

while (result == -1 && errno == EINTR)
result = ::recv(endpoint, reinterpret_cast<char*>(buffer),
length, noSignal);

if (result == -1)
throw std::system_error{errno, std::system_category(), "Failed to read data"};
#endif // defined(_WIN32) || defined(__CYGWIN__)
return static_cast<std::size_t>(result);
}

private:
enum class SelectType
{
read,
write
};

void select(const SelectType type, const std::int64_t timeout)
{
fd_set descriptorSet;
FD_ZERO(&descriptorSet);
FD_SET(endpoint, &descriptorSet);

#if defined(_WIN32) || defined(__CYGWIN__)
TIMEVAL selectTimeout{
static_cast<LONG>(timeout / 1000),
static_cast<LONG>((timeout % 1000) * 1000)
};
auto count = ::select(0,
(type == SelectType::read) ? &descriptorSet : nullptr,
(type == SelectType::write) ? &descriptorSet : nullptr,
nullptr,
(timeout >= 0) ? &selectTimeout : nullptr);

while (count == -1 && WSAGetLastError() == WSAEINTR)
count = ::select(0,
(type == SelectType::read) ? &descriptorSet : nullptr,
(type == SelectType::write) ? &descriptorSet : nullptr,
nullptr,
(timeout >= 0) ? &selectTimeout : nullptr);

if (count == -1)
throw std::system_error{WSAGetLastError(), std::system_category(), "Failed to select socket"};
else if (count == 0)
throw ResponseError{"Request timed out"};
#else
timeval selectTimeout{
static_cast<time_t>(timeout / 1000),
static_cast<suseconds_t>((timeout % 1000) * 1000)
};
auto count = ::select(endpoint + 1,
(type == SelectType::read) ? &descriptorSet : nullptr,
(type == SelectType::write) ? &descriptorSet : nullptr,
nullptr,
(timeout >= 0) ? &selectTimeout : nullptr);

while (count == -1 && errno == EINTR)
count = ::select(endpoint + 1,
(type == SelectType::read) ? &descriptorSet : nullptr,
(type == SelectType::write) ? &descriptorSet : nullptr,
nullptr,
(timeout >= 0) ? &selectTimeout : nullptr);

if (count == -1)
throw std::system_error{errno, std::system_category(), "Failed to select socket"};
else if (count == 0)
throw ResponseError{"Request timed out"};
#endif // defined(_WIN32) || defined(__CYGWIN__)
}

void close() noexcept
{
#if defined(_WIN32) || defined(__CYGWIN__)
closesocket(endpoint);
#else
::close(endpoint);
#endif // defined(_WIN32) || defined(__CYGWIN__)
}

#if defined(__unix__) && !defined(__APPLE__) && !defined(__CYGWIN__)
static constexpr int noSignal = MSG_NOSIGNAL;
#else
static constexpr int noSignal = 0;
#endif // defined(__unix__) && !defined(__APPLE__)

Type endpoint = invalid;
};

// RFC 7230, 3.2.3. WhiteSpace
template <typename C>
constexpr bool isWhiteSpaceChar(const C c) noexcept
{
return c == 0x20 || c == 0x09; // space or tab
};

// RFC 5234, Appendix B.1. Core Rules
template <typename C>
constexpr bool isDigitChar(const C c) noexcept
{
return c >= 0x30 && c <= 0x39; // 0 - 9
}

// RFC 5234, Appendix B.1. Core Rules
template <typename C>
constexpr bool isAlphaChar(const C c) noexcept
{
return
(c >= 0x61 && c <= 0x7A) || // a - z
(c >= 0x41 && c <= 0x5A); // A - Z
}

// RFC 7230, 3.2.6. Field Value Components
template <typename C>
constexpr bool isTokenChar(const C c) noexcept
{
return c == 0x21 || // !
c == 0x23 || // #
c == 0x24 || // $
c == 0x25 || // %
c == 0x26 || // &
c == 0x27 || // '
c == 0x2A || // *
c == 0x2B || // +
c == 0x2D || // -
c == 0x2E || // .
c == 0x5E || // ^
c == 0x5F || // _
c == 0x60 || // `
c == 0x7C || // |
c == 0x7E || // ~
isDigitChar(c) ||
isAlphaChar(c);
};

// RFC 5234, Appendix B.1. Core Rules
template <typename C>
constexpr bool isVisibleChar(const C c) noexcept
{
return c >= 0x21 && c <= 0x7E;
}

// RFC 7230, Appendix B. Collected ABNF
template <typename C>
constexpr bool isObsoleteTextChar(const C c) noexcept
{
return static_cast<unsigned char>(c) >= 0x80 &&
static_cast<unsigned char>(c) <= 0xFF;
}

template <class Iterator>
Iterator skipWhiteSpaces(const Iterator begin, const Iterator end)
{
auto i = begin;
for (i = begin; i != end; ++i)
if (!isWhiteSpaceChar(*i))
break;

return i;
}

// RFC 5234, Appendix B.1. Core Rules
template <typename T, typename C, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
constexpr T digitToUint(const C c)
{
// DIGIT
return (c >= 0x30 && c <= 0x39) ? static_cast<T>(c - 0x30) : // 0 - 9
throw ResponseError{"Invalid digit"};
}

// RFC 5234, Appendix B.1. Core Rules
template <typename T, typename C, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
constexpr T hexDigitToUint(const C c)
{
// HEXDIG
return (c >= 0x30 && c <= 0x39) ? static_cast<T>(c - 0x30) : // 0 - 9
(c >= 0x41 && c <= 0x46) ? static_cast<T>(c - 0x41) + T(10) : // A - Z
(c >= 0x61 && c <= 0x66) ? static_cast<T>(c - 0x61) + T(10) : // a - z, some services send lower-case hex digits
throw ResponseError{"Invalid hex digit"};
}

// RFC 3986, 3. Syntax Components
template <class Iterator>
Uri parseUri(const Iterator begin, const Iterator end)
{
Uri result;

// RFC 3986, 3.1. Scheme
auto i = begin;
if (i == end || !isAlphaChar(*begin))
throw RequestError{"Invalid scheme"};

result.scheme.push_back(*i++);

for (; i != end && (isAlphaChar(*i) || isDigitChar(*i) || *i == '+' || *i == '-' || *i == '.'); ++i)
result.scheme.push_back(*i);

if (i == end || *i++ != ':')
throw RequestError{"Invalid scheme"};
if (i == end || *i++ != '/')
throw RequestError{"Invalid scheme"};
if (i == end || *i++ != '/')
throw RequestError{"Invalid scheme"};

// RFC 3986, 3.2. Authority
std::string authority = std::string(i, end);

// RFC 3986, 3.5. Fragment
const auto fragmentPosition = authority.find('#');
if (fragmentPosition != std::string::npos)
{
result.fragment = authority.substr(fragmentPosition + 1);
authority.resize(fragmentPosition); // remove the fragment part
}

// RFC 3986, 3.4. Query
const auto queryPosition = authority.find('?');
if (queryPosition != std::string::npos)
{
result.query = authority.substr(queryPosition + 1);
authority.resize(queryPosition); // remove the query part
}

// RFC 3986, 3.3. Path
const auto pathPosition = authority.find('/');
if (pathPosition != std::string::npos)
{
// RFC 3986, 3.3. Path
result.path = authority.substr(pathPosition);
authority.resize(pathPosition);
}
else
result.path = "/";

// RFC 3986, 3.2.1. User Information
std::string userinfo;
const auto hostPosition = authority.find('@');
if (hostPosition != std::string::npos)
{
userinfo = authority.substr(0, hostPosition);

const auto passwordPosition = userinfo.find(':');
if (passwordPosition != std::string::npos)
{
result.user = userinfo.substr(0, passwordPosition);
result.password = userinfo.substr(passwordPosition + 1);
}
else
result.user = userinfo;

result.host = authority.substr(hostPosition + 1);
}
else
result.host = authority;

// RFC 3986, 3.2.2. Host
const auto portPosition = result.host.find(':');
if (portPosition != std::string::npos)
{
// RFC 3986, 3.2.3. Port
result.port = result.host.substr(portPosition + 1);
result.host.resize(portPosition);
}

return result;
}

// RFC 7230, 2.6. Protocol Versioning
template <class Iterator>
std::pair<Iterator, HttpVersion> parseHttpVersion(const Iterator begin, const Iterator end)
{
auto i = begin;

if (i == end || *i++ != 'H')
throw ResponseError{"Invalid HTTP version"};
if (i == end || *i++ != 'T')
throw ResponseError{"Invalid HTTP version"};
if (i == end || *i++ != 'T')
throw ResponseError{"Invalid HTTP version"};
if (i == end || *i++ != 'P')
throw ResponseError{"Invalid HTTP version"};
if (i == end || *i++ != '/')
throw ResponseError{"Invalid HTTP version"};

if (i == end)
throw ResponseError{"Invalid HTTP version"};

const auto majorVersion = digitToUint<std::uint16_t>(*i++);

if (i == end || *i++ != '.')
throw ResponseError{"Invalid HTTP version"};

if (i == end)
throw ResponseError{"Invalid HTTP version"};

const auto minorVersion = digitToUint<std::uint16_t>(*i++);

return {i, HttpVersion{majorVersion, minorVersion}};
}

// RFC 7230, 3.1.2. Status Line
template <class Iterator>
std::pair<Iterator, std::uint16_t> parseStatusCode(const Iterator begin, const Iterator end)
{
std::uint16_t result = 0;

auto i = begin;
while (i != end && isDigitChar(*i))
result = static_cast<std::uint16_t>(result * 10U) + digitToUint<std::uint16_t>(*i++);

if (std::distance(begin, i) != 3)
throw ResponseError{"Invalid status code"};

return {i, result};
}

// RFC 7230, 3.1.2. Status Line
template <class Iterator>
std::pair<Iterator, std::string> parseReasonPhrase(const Iterator begin, const Iterator end)
{
std::string result;

auto i = begin;
for (; i != end && (isWhiteSpaceChar(*i) || isVisibleChar(*i) || isObsoleteTextChar(*i)); ++i)
result.push_back(static_cast<char>(*i));

return {i, std::move(result)};
}

// RFC 7230, 3.2.6. Field Value Components
template <class Iterator>
std::pair<Iterator, std::string> parseToken(const Iterator begin, const Iterator end)
{
std::string result;

auto i = begin;
for (; i != end && isTokenChar(*i); ++i)
result.push_back(static_cast<char>(*i));

if (result.empty())
throw ResponseError{"Invalid token"};

return {i, std::move(result)};
}

// RFC 7230, 3.2. Header Fields
template <class Iterator>
std::pair<Iterator, std::string> parseFieldValue(const Iterator begin, const Iterator end)
{
std::string result;

auto i = begin;
for (; i != end && (isWhiteSpaceChar(*i) || isVisibleChar(*i) || isObsoleteTextChar(*i)); ++i)
result.push_back(static_cast<char>(*i));

// trim white spaces
result.erase(std::find_if(result.rbegin(), result.rend(), [](const char c) noexcept {
return !isWhiteSpaceChar(c);
}).base(), result.end());

return {i, std::move(result)};
}

// RFC 7230, 3.2. Header Fields
template <class Iterator>
std::pair<Iterator, std::string> parseFieldContent(const Iterator begin, const Iterator end)
{
std::string result;

auto i = begin;

for (;;)
{
const auto fieldValueResult = parseFieldValue(i, end);
i = fieldValueResult.first;
result += fieldValueResult.second;

// Handle obsolete fold as per RFC 7230, 3.2.4. Field Parsing
// Obsolete folding is known as linear white space (LWS) in RFC 2616, 2.2 Basic Rules
auto obsoleteFoldIterator = i;
if (obsoleteFoldIterator == end || *obsoleteFoldIterator++ != '\r')
break;

if (obsoleteFoldIterator == end || *obsoleteFoldIterator++ != '\n')
break;

if (obsoleteFoldIterator == end || !isWhiteSpaceChar(*obsoleteFoldIterator++))
break;

result.push_back(' ');
i = obsoleteFoldIterator;
}

return {i, std::move(result)};
}

// RFC 7230, 3.2. Header Fields
template <class Iterator>
std::pair<Iterator, HeaderField> parseHeaderField(const Iterator begin, const Iterator end)
{
auto tokenResult = parseToken(begin, end);
auto i = tokenResult.first;
auto fieldName = std::move(tokenResult.second);

if (i == end || *i++ != ':')
throw ResponseError{"Invalid header"};

i = skipWhiteSpaces(i, end);

auto valueResult = parseFieldContent(i, end);
i = valueResult.first;
auto fieldValue = std::move(valueResult.second);

if (i == end || *i++ != '\r')
throw ResponseError{"Invalid header"};

if (i == end || *i++ != '\n')
throw ResponseError{"Invalid header"};

return {i, {std::move(fieldName), std::move(fieldValue)}};
}

// RFC 7230, 3.1.2. Status Line
template <class Iterator>
std::pair<Iterator, Status> parseStatusLine(const Iterator begin, const Iterator end)
{
const auto httpVersionResult = parseHttpVersion(begin, end);
auto i = httpVersionResult.first;

if (i == end || *i++ != ' ')
throw ResponseError{"Invalid status line"};

const auto statusCodeResult = parseStatusCode(i, end);
i = statusCodeResult.first;

if (i == end || *i++ != ' ')
throw ResponseError{"Invalid status line"};

auto reasonPhraseResult = parseReasonPhrase(i, end);
i = reasonPhraseResult.first;

if (i == end || *i++ != '\r')
throw ResponseError{"Invalid status line"};

if (i == end || *i++ != '\n')
throw ResponseError{"Invalid status line"};

return {i, Status{
httpVersionResult.second,
statusCodeResult.second,
std::move(reasonPhraseResult.second)
}};
}

// RFC 7230, 4.1. Chunked Transfer Coding
template <typename T, class Iterator, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
T stringToUint(const Iterator begin, const Iterator end)
{
T result = 0;
for (auto i = begin; i != end; ++i)
result = T(10U) * result + digitToUint<T>(*i);

return result;
}

template <typename T, class Iterator, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr>
T hexStringToUint(const Iterator begin, const Iterator end)
{
T result = 0;
for (auto i = begin; i != end; ++i)
result = T(16U) * result + hexDigitToUint<T>(*i);

return result;
}

// RFC 7230, 3.1.1. Request Line
inline std::string encodeRequestLine(const std::string& method, const std::string& target)
{
return method + " " + target + " HTTP/1.1\r\n";
}

// RFC 7230, 3.2. Header Fields
inline std::string encodeHeaderFields(const HeaderFields& headerFields)
{
std::string result;
for (const auto& headerField : headerFields)
{
if (headerField.first.empty())
throw RequestError{"Invalid header field name"};

for (const auto c : headerField.first)
if (!isTokenChar(c))
throw RequestError{"Invalid header field name"};

for (const auto c : headerField.second)
if (!isWhiteSpaceChar(c) && !isVisibleChar(c) && !isObsoleteTextChar(c))
throw RequestError{"Invalid header field value"};

result += headerField.first + ": " + headerField.second + "\r\n";
}

return result;
}

// RFC 4648, 4. Base 64 Encoding
template <class Iterator>
std::string encodeBase64(const Iterator begin, const Iterator end)
{
constexpr std::array<char, 64> chars{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};

std::string result;
std::size_t c = 0;
std::array<std::uint8_t, 3> charArray;

for (auto i = begin; i != end; ++i)
{
charArray[c++] = static_cast<std::uint8_t>(*i);
if (c == 3)
{
result += chars[static_cast<std::uint8_t>((charArray[0] & 0xFC) >> 2)];
result += chars[static_cast<std::uint8_t>(((charArray[0] & 0x03) << 4) + ((charArray[1] & 0xF0) >> 4))];
result += chars[static_cast<std::uint8_t>(((charArray[1] & 0x0F) << 2) + ((charArray[2] & 0xC0) >> 6))];
result += chars[static_cast<std::uint8_t>(charArray[2] & 0x3f)];
c = 0;
}
}

if (c)
{
result += chars[static_cast<std::uint8_t>((charArray[0] & 0xFC) >> 2)];

if (c == 1)
result += chars[static_cast<std::uint8_t>((charArray[0] & 0x03) << 4)];
else // c == 2
{
result += chars[static_cast<std::uint8_t>(((charArray[0] & 0x03) << 4) + ((charArray[1] & 0xF0) >> 4))];
result += chars[static_cast<std::uint8_t>((charArray[1] & 0x0F) << 2)];
}

while (++c < 4) result += '='; // padding
}

return result;
}

inline std::vector<std::uint8_t> encodeHtml(const Uri& uri,
const std::string& method,
const std::vector<uint8_t>& body,
HeaderFields headerFields)
{
if (uri.scheme != "http")
throw RequestError{"Only HTTP scheme is supported"};

// RFC 7230, 5.3. Request Target
const std::string requestTarget = uri.path + (uri.query.empty() ? "" : '?' + uri.query);

// RFC 7230, 5.4. Host
headerFields.push_back({"Host", uri.host});

// RFC 7230, 3.3.2. Content-Length
headerFields.push_back({"Content-Length", std::to_string(body.size())});

// RFC 7617, 2. The 'Basic' Authentication Scheme
if (!uri.user.empty() || !uri.password.empty())
{
std::string userinfo = uri.user + ':' + uri.password;
headerFields.push_back({"Authorization", "Basic " + encodeBase64(userinfo.begin(), userinfo.end())});
}

const auto headerData = encodeRequestLine(method, requestTarget) +
encodeHeaderFields(headerFields) +
"\r\n";

std::vector<uint8_t> result(headerData.begin(), headerData.end());
result.insert(result.end(), body.begin(), body.end());

return result;
}
}

class Request final
{
public:
explicit Request(const std::string& uriString,
const InternetProtocol protocol = InternetProtocol::V4):
internetProtocol{protocol},
uri{parseUri(uriString.begin(), uriString.end())}
{
}

Response send(const std::string& method = "GET",
const std::string& body = "",
const HeaderFields& headerFields = {},
const std::chrono::milliseconds timeout = std::chrono::milliseconds{-1})
{
return send(method,
std::vector<uint8_t>(body.begin(), body.end()),
headerFields,
timeout);
}

Response send(const std::string& method,
const std::vector<uint8_t>& body,
const HeaderFields& headerFields = {},
const std::chrono::milliseconds timeout = std::chrono::milliseconds{-1})
{
const auto stopTime = std::chrono::steady_clock::now() + timeout;

if (uri.scheme != "http")
throw RequestError{"Only HTTP scheme is supported"};

addrinfo hints = {};
hints.ai_family = getAddressFamily(internetProtocol);
hints.ai_socktype = SOCK_STREAM;

const char* port = uri.port.empty() ? "80" : uri.port.c_str();

addrinfo* info;
if (getaddrinfo(uri.host.c_str(), port, &hints, &info) != 0)
throw std::system_error{getLastError(), std::system_category(), "Failed to get address info of " + uri.host};

const std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> addressInfo{info, freeaddrinfo};

const auto requestData = encodeHtml(uri, method, body, headerFields);

Socket socket{internetProtocol};

const auto getRemainingMilliseconds = [](const std::chrono::steady_clock::time_point time) noexcept -> std::int64_t {
const auto now = std::chrono::steady_clock::now();
const auto remainingTime = std::chrono::duration_cast<std::chrono::milliseconds>(time - now);
return (remainingTime.count() > 0) ? remainingTime.count() : 0;
};

// take the first address from the list
socket.connect(addressInfo->ai_addr, static_cast<socklen_t>(addressInfo->ai_addrlen),
(timeout.count() >= 0) ? getRemainingMilliseconds(stopTime) : -1);

auto remaining = requestData.size();
auto sendData = requestData.data();

// send the request
while (remaining > 0)
{
const auto size = socket.send(sendData, remaining,
(timeout.count() >= 0) ? getRemainingMilliseconds(stopTime) : -1);
remaining -= size;
sendData += size;
}

std::array<std::uint8_t, 4096> tempBuffer;
constexpr std::array<std::uint8_t, 2> crlf = {'\r', '\n'};
constexpr std::array<std::uint8_t, 4> headerEnd = {'\r', '\n', '\r', '\n'};
Response response;
std::vector<std::uint8_t> responseData;
bool parsingBody = false;
bool contentLengthReceived = false;
std::size_t contentLength = 0U;
bool chunkedResponse = false;
std::size_t expectedChunkSize = 0U;
bool removeCrlfAfterChunk = false;

// read the response
for (;;)
{
const auto size = socket.recv(tempBuffer.data(), tempBuffer.size(),
(timeout.count() >= 0) ? getRemainingMilliseconds(stopTime) : -1);
if (size == 0) // disconnected
return response;

responseData.insert(responseData.end(), tempBuffer.begin(), tempBuffer.begin() + size);

if (!parsingBody)
{
// RFC 7230, 3. Message Format
// Empty line indicates the end of the header section (RFC 7230, 2.1. Client/Server Messaging)
const auto endIterator = std::search(responseData.cbegin(), responseData.cend(),
headerEnd.cbegin(), headerEnd.cend());
if (endIterator == responseData.cend()) break; // two consecutive CRLFs not found

const auto headerBeginIterator = responseData.cbegin();
const auto headerEndIterator = endIterator + 2;

auto statusLineResult = parseStatusLine(headerBeginIterator, headerEndIterator);
auto i = statusLineResult.first;

response.status = std::move(statusLineResult.second);

for (;;)
{
auto headerFieldResult = parseHeaderField(i, headerEndIterator);
i = headerFieldResult.first;

auto fieldName = std::move(headerFieldResult.second.first);
const auto toLower = [](const char c) noexcept {
return (c >= 'A' && c <= 'Z') ? c - ('A' - 'a') : c;
};
std::transform(fieldName.begin(), fieldName.end(), fieldName.begin(), toLower);

auto fieldValue = std::move(headerFieldResult.second.second);

if (fieldName == "transfer-encoding")
{
// RFC 7230, 3.3.1. Transfer-Encoding
if (fieldValue == "chunked")
chunkedResponse = true;
else
throw ResponseError{"Unsupported transfer encoding: " + fieldValue};
}
else if (fieldName == "content-length")
{
// RFC 7230, 3.3.2. Content-Length
contentLength = stringToUint<std::size_t>(fieldValue.cbegin(), fieldValue.cend());
contentLengthReceived = true;
response.body.reserve(contentLength);
}

response.headerFields.push_back({std::move(fieldName), std::move(fieldValue)});

if (i == headerEndIterator)
break;
}

responseData.erase(responseData.cbegin(), headerEndIterator + 2);
parsingBody = true;
}

if (parsingBody)
{
// Content-Length must be ignored if Transfer-Encoding is received (RFC 7230, 3.2. Content-Length)
if (chunkedResponse)
{
// RFC 7230, 4.1. Chunked Transfer Coding
for (;;)
{
if (expectedChunkSize > 0)
{
const auto toWrite = (std::min)(expectedChunkSize, responseData.size());
response.body.insert(response.body.end(), responseData.begin(),
responseData.begin() + static_cast<std::ptrdiff_t>(toWrite));
responseData.erase(responseData.begin(),
responseData.begin() + static_cast<std::ptrdiff_t>(toWrite));
expectedChunkSize -= toWrite;

if (expectedChunkSize == 0) removeCrlfAfterChunk = true;
if (responseData.empty()) break;
}
else
{
if (removeCrlfAfterChunk)
{
if (responseData.size() < 2) break;

if (!std::equal(crlf.begin(), crlf.end(), responseData.begin()))
throw ResponseError{"Invalid chunk"};

removeCrlfAfterChunk = false;
responseData.erase(responseData.begin(), responseData.begin() + 2);
}

const auto i = std::search(responseData.begin(), responseData.end(),
crlf.begin(), crlf.end());

if (i == responseData.end()) break;

expectedChunkSize = detail::hexStringToUint<std::size_t>(responseData.begin(), i);
responseData.erase(responseData.begin(), i + 2);

if (expectedChunkSize == 0)
return response;
}
}
}
else
{
response.body.insert(response.body.end(), responseData.begin(), responseData.end());
responseData.clear();

// got the whole content
if (contentLengthReceived && response.body.size() >= contentLength)
return response;
}
}
}

return response;
}

private:
#if defined(_WIN32) || defined(__CYGWIN__)
WinSock winSock;
#endif // defined(_WIN32) || defined(__CYGWIN__)
InternetProtocol internetProtocol;
Uri uri;
};
}

#endif // HTTPREQUEST_HPP

参考资料:

网络编程(Win/Linux):理解select函数并实现IO复用服务器端 - 戈小戈 - 博客园

Socket通信——C++服务器端和Java客户端_xcy6666的博客-CSDN博客

C++和java通过Socket批量发送和接收文件(C++客户端发送,java服务端接收)_wengtengfan的博客-CSDN博客_socket 批量发送

java 发送字节流图片,c++接收二进制流_51CTO博客_c++读取二进制文件

C++和java通过Socket批量发送和接收文件(C++客户端发送,java服务端接收)_wengtengfan的博客-CSDN博客_socket 批量发送

Java客户端上传图片(文件)到c++服务器 - c++语言程序开发技术文章_c++编程 - 红黑联盟

https://github.com/katiejyoung/file-transfer-system/blob/master/FTClient.java

file-transfer-system/ftserver.c at master · katiejyoung/file-transfer-system · GitHub

Socket通信——C++服务器端和Java客户端_xcy6666的博客-CSDN博客


java:

Java实现socket通信详解(UDP/TCP)c/s模式_寒风凋零的博客-CSDN博客

使用Java完成Socket通信_牛言牛语的博客-CSDN博客_java socket通信