-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtcp.hpp
1567 lines (1328 loc) · 51 KB
/
mtcp.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
#pragma once
#ifdef _WIN32
//define something for Windows (32-bit and 64-bit, this part is common)
#define MTCP_OS_WINDOWS
#define MTCP_OS "WINDOWS"
#ifdef _WIN64
//define something for Windows (64-bit only)
#else
//define something for Windows (32-bit only)
#endif
#elif __APPLE__
#include "TargetConditionals.h"
#if TARGET_IPHONE_SIMULATOR
// iOS Simulator
#define MTCP_OS_IOS_SIMULATOR
#define MTCP_OS "IOS_SIMULATOR"
#elif TARGET_OS_IPHONE
// iOS device
#define MTCP_OS_IOS_PHONE
#define MTCP_OS "IOS_PHONE"
#elif TARGET_OS_MAC
// Other kinds of Mac OS
#define MTCP_OS_MAC
#define MTCP_OS "MAC"
#else
# error "Unknown Apple platform"
#endif
#elif __ANDROID__
// android
#define MTCP_OS_ANDROID
#define MTCP_OS "ANDROID"
#elif __linux__
// linux
#define MTCP_OS_LINUX
#define MTCP_OS "LINUX"
#elif __unix__ // all unices not caught above
// Unix
#define MTCP_OS_UNIX
#define MTCP_OS "UNIX"
#elif defined(_POSIX_VERSION)
// POSIX
#define MTCP_OS_POSIX "POSIX"
#define MTCP_OS "POSIX"
#else
# error "Unknown compiler"
#endif
#if (defined MTCP_OS_WINDOWS)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#include <mswsock.h>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "Mswsock.lib")
typedef SOCKET mtcp_socket_t;
#define mtcp_invalid_socket INVALID_SOCKET
#else
#include <cstring>
#include<netdb.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
typedef int mtcp_socket_t;
#define mtcp_invalid_socket -1
void mtcp_handle_pipe(int sig) {}
#endif
#include <iostream>
#include <chrono>
#include <ctime>
#include <string>
#include <mutex>
#include <unordered_map>
#include <unordered_set>
#include <deque>
#include <list>
#include <memory>
#include <map>
#include <set>
#include <vector>
#include <forward_list>
#include <functional>
#define mtcp_invalid_timer_id 0
namespace mtcp
{
//message access
class session_t;
class callback_t{
public:
virtual bool on_open(session_t* session) { return true; }
virtual bool on_recv(session_t* session, unsigned int sequence, const char *data, std::size_t len) { return true; }
virtual bool on_send(session_t* session, unsigned int sequence, int result, std::size_t cost_time) { return true; }
virtual bool on_timeout(session_t* session) { return false; }
virtual void on_close(session_t* session) { return; }
};
typedef std::function<unsigned int(session_t* session, const char *data, std::size_t len)> send_t;
typedef std::function<bool(session_t* session)> active_callback_t;
typedef std::function<bool(session_t* session, unsigned int sequence, const char *data, std::size_t len)> recv_callback_t;
typedef std::function<bool(session_t* session, unsigned int sequence, int result, std::size_t cost_time)> send_callback_t;
typedef std::function<bool(session_t* session)> timeout_callback_t;
typedef std::function<void(session_t* session)> close_callback_t;
typedef std::deque<session_t*> delay_close_queue_t;
static inline bool before(unsigned int seq1, unsigned int seq2){
return (int)(seq1 - seq2) < 0;
}
static inline bool after(unsigned int seq1, unsigned int seq2){
return before(seq2, seq1);
}
static inline bool contain(unsigned int left, unsigned int right, unsigned int seq){
return (left == seq || before(left, seq)) && ((right == seq) || after(right, seq));
}
//mtcp inner protocol define
namespace protocol{
enum {
e_mss = 65400,
e_wnd = 256,
e_rtoc = 3,
};
enum {
e_sync = 0,
e_fin = 1,
e_alive = 2,
e_close = 3,
};
class slot_t{
public:
slot_t(){
clear();
}
void set(unsigned int pos, bool val){
pos &= 0x1F;
unsigned int tmp = 1 << (7 - pos % 7);
if (val)
slot[pos >> 3] |= tmp;
else
slot[pos >> 3] &= ~tmp;
}
bool get(unsigned int pos){
pos &= 0x1F;
return (slot[pos >> 3] & (1 << (7 - pos % 7))) != 0;
}
void clear(){
memset(slot, 0, sizeof(slot));
}
private:
unsigned char slot[4];
};
#pragma pack(push, 1)
struct header_t{
header_t(){
memset(&flags, 0, sizeof(flags));
}
enum {
e_sync = 1 << 7,
e_push = 1 << 6,
e_begin = 1 << 5,
e_end = 1 << 4,
e_ack = 1 << 3,
e_sack = 1 << 2,
e_heart = 1 << 1,
e_fin = 1,
};
void hton(){
seq = htonl(seq);
group = htonl(group);
token = htons(token);
}
void ntoh(){
seq = ntohl(seq);
group = ntohl(group);
token = ntohs(token);
}
struct {
unsigned char sync : 1;
unsigned char push : 1;
unsigned char begin : 1;
unsigned char end : 1;
unsigned char ack : 1;
unsigned char s_ack : 1;
unsigned char heartbeat : 1;
unsigned char fin : 1;
} flags;
unsigned short token = 0;
unsigned int seq = 0;
unsigned int group = 0;
};
#pragma pack(pop)
class message_t {
friend class session_t;
public:
message_t(unsigned int token){
data_.resize(sizeof(header_t));
head.token = token;
}
bool operator <(const message_t &other){
return before(head.seq, other.head.seq);
}
bool operator ==(const message_t &other){
return head.seq == other.head.seq;
}
static bool compare(const protocol::message_t * a, const protocol::message_t * b){
return before(a->head.seq, b->head.seq);
}
static bool equal(const protocol::message_t * a, const protocol::message_t * b){
return a->head.seq == b->head.seq;
}
char *data(){
return (char*)data_.data() + sizeof(header_t);
}
size_t size() {
return data_.size() - sizeof(header_t);
}
void assign(const char* data, std::size_t len){
data_.resize(len + sizeof(header_t));
if (len > 0)
memcpy((char*)data_.data() + sizeof(header_t), data, len);
}
void append(const char* data, std::size_t len){
data_.append(data, len);
}
void insert(const char* data, std::size_t len){
data_.insert(sizeof(header_t), data, len);
}
void clear(){
data_.resize(sizeof(header_t));
}
const std::string &encode(){
// head.crc = crc((const unsigned char *)data(), size());
header_t *h = (header_t*)data_.data();
memcpy(h, &head, sizeof(header_t));
h->hton();
return data_;
}
const std::string &raw_data(){
return data_;
}
static unsigned short crc(const unsigned char *data, std::size_t len){
unsigned short ret = 0;
for (std::size_t i = 1; i < len; i++)
ret += *(++data);
return ret;
}
bool decode(const char* data, std::size_t len){
if (len < sizeof(header_t) || len > e_mss + sizeof(header_t))
return false;
header_t *h = (header_t*)data;
h->ntoh();
// if (h->crc != crc((const unsigned char*)data + sizeof(header_t), len - sizeof(header_t)))
// return false;
memcpy(&head, h, sizeof(header_t));
data_.assign(data, len);
return true;
}
public:
header_t head;
std::string data_;
unsigned int send_count = 0;
std::size_t timestamp = 0;
};
}
struct group_compare{
bool operator()(const unsigned int &a, const unsigned int & b){
return before(a, b);
}
};
struct message_compare{
bool operator()(const protocol::message_t * a, const protocol::message_t * b){
return before(a->head.seq, b->head.seq);
}
};
using namespace std;
struct address_info_t{
std::string ip;
unsigned short port;
};
typedef std::function<bool()> timer_callback_t;
static inline std::size_t get_timestamp()
{
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
}
struct timer_t
{
std::size_t id;
std::size_t delay;
std::size_t timestamp;
timer_callback_t callback;
};
class timer_manager : std::multimap <std::size_t, timer_t>{
public:
std::size_t do_timer() {
if (empty())
return 0;
std::size_t now = get_timestamp();
while (size() > 0)
{
auto iter = begin();
if (iter->first <= now)
{
timer_t item = iter->second;
erase(iter);
if (item.callback()) {
item.timestamp = now + item.delay;
emplace(item.timestamp, std::move(item));
}
}
else {
break;
}
}
return size() > 0 ? begin()->first - now : 0;
}
std::size_t set_timer(std::size_t delay, timer_callback_t cb) {
timer_t item;
item.id = ++_id;
item.delay = delay;
item.timestamp = get_timestamp() + delay;
item.callback = std::move(cb);
auto ret = item.id;
emplace(item.timestamp, std::move(item));
return ret;
}
bool cancel_timer(std::size_t id) {
if (id == mtcp_invalid_timer_id)
return false;
for (auto iter = begin(); iter != end(); ++iter) {
if (id == iter->second.id) {
erase(iter);
return true;
}
}
return false;
}
private:
std::size_t _id = 0;
};
class socket{
friend class proactor_engine;
public:
static bool parse_addr(const string &addr, address_info_t &ret) {
std::size_t pos = addr.find(":");
if (pos == string::npos)
return false;
ret.ip.assign(addr.c_str(), pos);
ret.port = atoi(addr.c_str() + pos + 1);
return !ret.ip.empty();
}
static bool get_local_addr(mtcp_socket_t fd, address_info_t &ret) {
struct sockaddr_in sa;
socklen_t len = sizeof(sa);
if (!getsockname(fd, (struct sockaddr *)&sa, &len))
{
ret.ip = inet_ntoa(sa.sin_addr);
ret.port = ntohs(sa.sin_port);
return true;
}
return false;
}
static bool get_remote_addr(mtcp_socket_t fd, address_info_t &ret) {
struct sockaddr_in sa;
socklen_t len = sizeof(sa);
if (!getpeername(fd, (struct sockaddr *)&sa, &len))
{
ret.ip = inet_ntoa(sa.sin_addr);
ret.port = ntohs(sa.sin_port);
return true;
}
return false;
}
static int get_error() {
#ifdef MTCP_OS_WINDOWS
return WSAGetLastError();
#else
return errno;
#endif
}
static const char *get_error_str(int err){
#ifdef MTCP_OS_WINDOWS
#pragma warning(disable:4996)
#endif
return strerror(err);
}
static void dump_error(){
int err = get_error();
printf("error:%d, %s\n", err, get_error_str(err));
}
static void set_nodelay(mtcp_socket_t fd, bool val = true)
{
int opt = val ? 1 : 0;
::setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, sizeof(opt));
}
static void set_noblock(mtcp_socket_t fd, bool val = true)
{
#if (defined MTCP_OS_WINDOWS)
unsigned long opt = val ? 1 : 0;
::ioctlsocket(fd, FIONBIO, &opt);
#else
int flags = fcntl(fd, F_GETFL, 0);
if (val)
flags |= O_NONBLOCK;
else
flags &= ~O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
#endif
}
/*
int tcp_connect(const char *addr, short port)
{
char ip[128];
memset(ip, 0, sizeof(ip));
strcpy(ip, addr);
void* svraddr = nullptr;
int error = -1, svraddr_len;
bool ret = true;
struct sockaddr_in svraddr_4;
struct sockaddr_in6 svraddr_6;
//��ȡ����Э��
struct addrinfo *result;
error = getaddrinfo(ip, NULL, NULL, &result);
if (error != 0)
return -1;
struct sockaddr *sa = result->ai_addr;
socklen_t maxlen = 128;
int fd = -1;
switch (sa->sa_family)
{
case AF_INET://ipv4
{
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
ret = false;
break;
}
char *tmp = (char *)ip;
if (inet_ntop(AF_INET, (void *)&(((struct sockaddr_in *) sa)->sin_addr), tmp,
maxlen) == NULL) {
ret = false;
break;
}
svraddr_4.sin_family = AF_INET;
svraddr_4.sin_addr.s_addr = inet_addr(ip);
svraddr_4.sin_port = htons(port);
svraddr_len = sizeof(svraddr_4);
svraddr = &svraddr_4;
break;
}
case AF_INET6://ipv6
{
if ((fd = socket(AF_INET6, SOCK_STREAM, 0)) < 0) {
ret = false;
break;
}
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *) sa)->sin6_addr), ip, maxlen);
memset(&svraddr_6, 0, sizeof(svraddr_6));
svraddr_6.sin6_family = AF_INET6;
svraddr_6.sin6_port = htons(port);
if (inet_pton(AF_INET6, ip, &svraddr_6.sin6_addr) < 0) {
ret = false;
break;
}
svraddr_len = sizeof(svraddr_6);
svraddr = &svraddr_6;
break;
}
default: {
ret = false;
}
}
freeaddrinfo(result);
if (!ret)
{
close_socket(fd);
return -1;
}
set_noblock(fd);
int nret = ::connect(fd, (struct sockaddr*)svraddr, svraddr_len);
if (nret != 0)
{
int err = get_error();
#ifdef _WIN32
if (err != WSAEINPROGRESS && err != WSAEWOULDBLOCK)
{
close_socket(fd);
return -1;
}
#else
if (err != EINPROGRESS && err != EWOULDBLOCK)
{
close_socket(fd);
return -1;
}
#endif
else
{
struct timeval timeout = { 2, 0 };
fd_set wset, rset;
FD_ZERO(&wset);
FD_ZERO(&rset);
FD_SET(fd, &wset);
FD_SET(fd, &rset);
int res = select(fd + 1, &rset, &wset, NULL, &timeout);
if (res <= 0)
{
goto CONNECT_ERROR;
}
else if (1 == res)
{
if (FD_ISSET(fd, &wset))
{
set_noblock(fd, true);
return fd;
}
else
{
goto CONNECT_ERROR;
}
}
}
}
else
{
return fd;
}
CONNECT_ERROR:
close_socket(fd);
return -1;
}
*/
static bool connect(mtcp_socket_t fd, const string &addr/*ip:port*/){
address_info_t info;
if (!parse_addr(addr, info))
return false;
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(info.port);
address.sin_addr.s_addr = inet_addr(info.ip.c_str());
return connect(fd, (struct sockaddr *)&address);
}
static bool connect(mtcp_socket_t fd, const struct sockaddr *addr/*ip:port*/){
auto rc = ::connect(fd, addr, sizeof(sockaddr_in));
return true;
}
static bool bind(mtcp_socket_t fd, const string &addr/*ip:port*/){
address_info_t info;
if (!parse_addr(addr, info))
return false;
int opt = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
#if (defined MTCP_OS_WINDOWS)
#else
#if (defined SO_REUSEPORT)
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
#endif
#endif
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(info.port);
address.sin_addr.s_addr = inet_addr(info.ip.c_str());
return ::bind(fd, (struct sockaddr *)&address, sizeof(address)) == 0;
}
static bool listen(mtcp_socket_t fd, int backlog){
return ::listen(fd, backlog) == 0;
}
static mtcp_socket_t accept(mtcp_socket_t fd) {
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
#ifdef MTCP_OS_WINDOWS
int addr_len = sizeof(addr);
#else
unsigned int addr_len = sizeof(addr);
#endif
return ::accept(fd, (sockaddr*)&addr, &addr_len);
}
static void close(mtcp_socket_t fd)
{
if (fd == mtcp_invalid_socket)
return;
#if (defined MTCP_OS_WINDOWS)
::closesocket(fd);
#else
::close(fd);
#endif
}
static mtcp_socket_t create(int af, int type, int protocol = 0)
{
init();
mtcp_socket_t s = mtcp_invalid_socket;
#if (defined MTCP_OS_WINDOWS)
af = PF_INET;
s = WSASocket(af, type, protocol, 0, 0, WSA_FLAG_OVERLAPPED);
#else
s = ::socket(af, type, protocol);
#endif
return s;
}
#if (defined MTCP_OS_WINDOWS)
static bool load_wsa_func(GUID &guid, void *&pfun) {
static once_flag t;
static mtcp_socket_t fd = mtcp_invalid_socket;
std::call_once(t, []{
fd = create(AF_INET, SOCK_STREAM, IPPROTO_TCP);
});
DWORD tmp = 0;
return ::WSAIoctl(fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid
, sizeof(guid), &pfun, sizeof(pfun), &tmp, NULL, NULL) != SOCKET_ERROR;
}
#endif
private:
static void init(){
#if (defined MTCP_OS_WINDOWS)
static once_flag t;
std::call_once(t, []{
WSADATA wsa_data;
WSAStartup(0x0201, &wsa_data);
});
#endif
}
};
class peer_t;
struct context
#if (defined MTCP_OS_WINDOWS)
: OVERLAPPED
#endif
{
enum {
e_recv = 0,
e_send = 1,
e_exit = 2
};
context()
{
buf.resize(protocol::e_mss + sizeof(protocol::header_t));
#if (defined MTCP_OS_WINDOWS)
memset(this, 0, sizeof(OVERLAPPED));
WSABuf.buf = (CHAR*)buf.data();
WSABuf.len = (ULONG)buf.size();
#endif
address.resize(sizeof(sockaddr_in));
}
int status = e_recv;
string buf;
#if (defined MTCP_OS_WINDOWS)
WSABUF WSABuf;
#endif
string address;
peer_t *peer;
};
class proactor_engine;
class peer_t;
class session_t;
typedef std::function<bool(bool, peer_t *peer)> peer_callback_t;
struct sequence_t{
unsigned int count = 0;
std::size_t timestamp = 0;
};
struct serial_t {
unsigned int left = 0;
unsigned int right = 0;
};
class session_t{
friend class proactor_engine;
friend class peer_t;
public:
enum {
e_server = 0,
e_server_peer = 1,
e_client = 2,
};
session_t(unsigned int token, callback_t *cb)
: local_token(token), callback(cb)
{
}
~session_t(){}
const address_info_t & get_local_addr(){
return local_addr_info;
}
const address_info_t & get_remote_addr(){
return remote_addr_info;
}
bool on_timer(){
std::size_t ts = get_timestamp();
if (recv_timestamp && ts - recv_timestamp > timeout * protocol::e_rtoc)
{
bool rc = callback->on_timeout(this);
if (!rc)
{
close();
return false;
}
else
{
recv_timestamp = ts;
}
}
if (!wait_ack_set.empty()) {
if (ts - (*wait_ack_set.begin())->timestamp > 40)
{
send(*wait_ack_set.begin());
}
}
flush();
if (recv_timestamp && ts - send_timestamp > timeout)
send_heartbeat();
return true;
}
unsigned int send(const char *data, std::size_t len) {
if (len == 0)
return 0;
unsigned int req_seq = ++req_sequence;
unsigned int count = (unsigned int)(len / protocol::e_mss + (len % protocol::e_mss ? 1 : 0));
sequence_t sequence_obj;
sequence_obj.count = count;
//std::cout << count << std::endl;
sequence_obj.timestamp = get_timestamp();
auto iter = sequence_map.insert(std::make_pair(req_seq, sequence_obj));
std::size_t pos = 0;
while (pos < len)
{
protocol::message_t * message = new protocol::message_t(local_token);
std::size_t cost = (len > pos + protocol::e_mss) ? protocol::e_mss : (len - pos);
message->head.group = req_seq;
message->head.flags.begin = pos == 0 ? 1 : 0;
message->head.flags.end = (len <= pos + protocol::e_mss) ? 1 : 0;
message->head.flags.push = 1;
message->head.flags.ack = 0;
message->head.flags.s_ack = 0;
message->head.flags.heartbeat = 0;
message->head.flags.fin = 0;
message->head.seq = ++seq;
message->assign(data + pos, cost);
message->encode();
pos += cost;
if (wait_ack_set.size() == protocol::e_wnd) {
wait_send.emplace_back(std::move(message));
}
else {
send(message);
wait_ack_set.emplace(std::move(message));
}
}
return req_seq;
}
void close(){
close(true);
}
private:
void close(bool local) {
reset();
if (local)
{
for (int i = 0; i < 3; i++)
send_fin();
}
if (type == e_client)
socket::close(fd);
else
callback->on_close(this);
}
void reset(){
seq = 0;
req_sequence = 0;
remote_commit_seq = 0;
for (auto iter : recv_map) {
for (auto iter2 : iter.second)
delete iter2;
}
recv_map.clear();
for (auto iter : wait_send)
delete iter;
wait_send.clear();
for (auto iter : wait_ack_set)
delete iter;
wait_ack_set.clear();
}
void on_recv(protocol::message_t * message){
if (message->head.flags.ack || message->head.flags.s_ack) {
on_ack(message);
delete message;
return;
}
//std::cout << message->head.seq << std::endl;
if (message->head.flags.push)
{
// send_ack(message->head.seq, message->head.group);
// return;
if (before(remote_commit_seq, message->head.seq))
{
auto iter = recv_map.find(message->head.group);
if (iter != recv_map.end())
{
group_message_t &group = iter->second;
auto sub_iter = group.insert(message);
if (!sub_iter.second)
{
send_ack(remote_commit_seq, message);
delete message;
}
else{
send_ack(consumer(), message);
}
}
else{
if (message->head.flags.begin && message->head.flags.end
&& message->head.seq == remote_commit_seq + 1)
{
remote_commit_seq = message->head.seq;
send_ack(remote_commit_seq, message);
callback->on_recv(this, message->head.group, message->data(), message->size());
delete message;
}
else {
group_message_t group = { message };
recv_map.emplace(message->head.group, std::move(group));
send_ack(consumer(), message);
}
}
}
else{
send_ack(remote_commit_seq, 0, true);
delete message;
}
}
flush();
}
void flush() {
while (wait_send.size() > 0 && wait_ack_set.size() < protocol::e_wnd) {
send(wait_send[0]);
wait_ack_set.insert(wait_send[0]);
wait_send.pop_front();
}
}
void check_sequence_count(unsigned int sequence){
auto iter = sequence_map.find(sequence);
if (iter != sequence_map.end()){
if (--iter->second.count == 0)
{
callback->on_send(this, iter->first, 0, get_timestamp() - iter->second.timestamp);
sequence_map.erase(iter);
}
}
}