Repository navigation
Expand file tree
/
Copy pathchannel.cpp
More file actions
814 lines (687 loc) · 23 KB
/
Copy pathchannel.cpp
File metadata and controls
814 lines (687 loc) · 23 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
/*
This source file is part of KBEngine
For the latest info, see http://www.kbengine.org/
Copyright (c) 2008-2016 KBEngine.
KBEngine is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
KBEngine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with KBEngine. If not, see <http://www.gnu.org/licenses/>.
*/
#include "channel.h"
#ifndef CODE_INLINE
#include "channel.inl"
#endif
#include "network/websocket_protocol.h"
#include "network/websocket_packet_filter.h"
#include "network/websocket_packet_reader.h"
#include "network/bundle.h"
#include "network/packet_reader.h"
#include "network/network_interface.h"
#include "network/tcp_packet_receiver.h"
#include "network/tcp_packet_sender.h"
#include "network/udp_packet_receiver.h"
#include "network/tcp_packet.h"
#include "network/udp_packet.h"
#include "network/message_handler.h"
#include "network/network_stats.h"
namespace KBEngine {
namespace Network
{
//-------------------------------------------------------------------------------------
static ObjectPool<Channel> _g_objPool("Channel");
ObjectPool<Channel>& Channel::ObjPool()
{
return _g_objPool;
}
//-------------------------------------------------------------------------------------
Channel* Channel::createPoolObject()
{
return _g_objPool.createObject();
}
//-------------------------------------------------------------------------------------
void Channel::reclaimPoolObject(Channel* obj)
{
_g_objPool.reclaimObject(obj);
}
//-------------------------------------------------------------------------------------
void Channel::destroyObjPool()
{
DEBUG_MSG(fmt::format("Channel::destroyObjPool(): size {}.\n",
_g_objPool.size()));
_g_objPool.destroy();
}
//-------------------------------------------------------------------------------------
size_t Channel::getPoolObjectBytes()
{
size_t bytes = sizeof(pNetworkInterface_) + sizeof(traits_) +
sizeof(id_) + sizeof(inactivityTimerHandle_) + sizeof(inactivityExceptionPeriod_) +
sizeof(lastReceivedTime_) + (bufferedReceives_.size() * sizeof(Packet*)) + sizeof(pPacketReader_)
+ sizeof(flags_) + sizeof(numPacketsSent_) + sizeof(numPacketsReceived_) + sizeof(numBytesSent_) + sizeof(numBytesReceived_)
+ sizeof(lastTickBytesReceived_) + sizeof(lastTickBytesSent_) + sizeof(pFilter_) + sizeof(pEndPoint_) + sizeof(pPacketReceiver_) + sizeof(pPacketSender_)
+ sizeof(proxyID_) + strextra_.size() + sizeof(channelType_)
+ sizeof(componentID_) + sizeof(pMsgHandlers_);
return bytes;
}
//-------------------------------------------------------------------------------------
Channel::SmartPoolObjectPtr Channel::createSmartPoolObj()
{
return SmartPoolObjectPtr(new SmartPoolObject<Channel>(ObjPool().createObject(), _g_objPool));
}
//-------------------------------------------------------------------------------------
void Channel::onReclaimObject()
{
this->clearState();
}
//-------------------------------------------------------------------------------------
Channel::Channel(NetworkInterface & networkInterface,
const EndPoint * pEndPoint, Traits traits, ProtocolType pt,
PacketFilterPtr pFilter, ChannelID id):
pNetworkInterface_(NULL),
traits_(traits),
protocoltype_(pt),
id_(id),
inactivityTimerHandle_(),
inactivityExceptionPeriod_(0),
lastReceivedTime_(0),
bundles_(),
pPacketReader_(0),
numPacketsSent_(0),
numPacketsReceived_(0),
numBytesSent_(0),
numBytesReceived_(0),
lastTickBytesReceived_(0),
lastTickBytesSent_(0),
pFilter_(pFilter),
pEndPoint_(NULL),
pPacketReceiver_(NULL),
pPacketSender_(NULL),
proxyID_(0),
strextra_(),
channelType_(CHANNEL_NORMAL),
componentID_(UNKNOWN_COMPONENT_TYPE),
pMsgHandlers_(NULL),
flags_(0)
{
this->clearBundle();
initialize(networkInterface, pEndPoint, traits, pt, pFilter, id);
}
//-------------------------------------------------------------------------------------
Channel::Channel():
pNetworkInterface_(NULL),
traits_(EXTERNAL),
protocoltype_(PROTOCOL_TCP),
id_(0),
inactivityTimerHandle_(),
inactivityExceptionPeriod_(0),
lastReceivedTime_(0),
bundles_(),
pPacketReader_(0),
// Stats
numPacketsSent_(0),
numPacketsReceived_(0),
numBytesSent_(0),
numBytesReceived_(0),
lastTickBytesReceived_(0),
lastTickBytesSent_(0),
pFilter_(NULL),
pEndPoint_(NULL),
pPacketReceiver_(NULL),
pPacketSender_(NULL),
proxyID_(0),
strextra_(),
channelType_(CHANNEL_NORMAL),
componentID_(UNKNOWN_COMPONENT_TYPE),
pMsgHandlers_(NULL),
flags_(0)
{
this->clearBundle();
}
//-------------------------------------------------------------------------------------
Channel::~Channel()
{
// DEBUG_MSG(fmt::format("Channel::~Channel(): {}\n", this->c_str()));
finalise();
}
//-------------------------------------------------------------------------------------
bool Channel::initialize(NetworkInterface & networkInterface,
const EndPoint * pEndPoint,
Traits traits,
ProtocolType pt,
PacketFilterPtr pFilter,
ChannelID id)
{
id_ = id;
protocoltype_ = pt;
traits_ = traits;
pFilter_ = pFilter;
pNetworkInterface_ = &networkInterface;
this->pEndPoint(pEndPoint);
KBE_ASSERT(pNetworkInterface_ != NULL);
KBE_ASSERT(pEndPoint_ != NULL);
if(protocoltype_ == PROTOCOL_TCP)
{
if(pPacketReceiver_)
{
if(pPacketReceiver_->type() == PacketReceiver::UDP_PACKET_RECEIVER)
{
SAFE_RELEASE(pPacketReceiver_);
pPacketReceiver_ = new TCPPacketReceiver(*pEndPoint_, *pNetworkInterface_);
}
}
else
{
pPacketReceiver_ = new TCPPacketReceiver(*pEndPoint_, *pNetworkInterface_);
}
KBE_ASSERT(pPacketReceiver_->type() == PacketReceiver::TCP_PACKET_RECEIVER);
// UDP不需要注册描述符
pNetworkInterface_->dispatcher().registerReadFileDescriptor(*pEndPoint_, pPacketReceiver_);
// 需要发送数据时再注册
// pPacketSender_ = new TCPPacketSender(*pEndPoint_, *pNetworkInterface_);
// pNetworkInterface_->dispatcher().registerWriteFileDescriptor(*pEndPoint_, pPacketSender_);
}
else
{
if(pPacketReceiver_)
{
if(pPacketReceiver_->type() == PacketReceiver::TCP_PACKET_RECEIVER)
{
SAFE_RELEASE(pPacketReceiver_);
pPacketReceiver_ = new UDPPacketReceiver(*pEndPoint_, *pNetworkInterface_);
}
}
else
{
pPacketReceiver_ = new UDPPacketReceiver(*pEndPoint_, *pNetworkInterface_);
}
KBE_ASSERT(pPacketReceiver_->type() == PacketReceiver::UDP_PACKET_RECEIVER);
}
pPacketReceiver_->pEndPoint(pEndPoint_);
if(pPacketSender_)
pPacketSender_->pEndPoint(pEndPoint_);
startInactivityDetection((traits_ == INTERNAL) ? g_channelInternalTimeout :
g_channelExternalTimeout,
(traits_ == INTERNAL) ? g_channelInternalTimeout / 2.f:
g_channelExternalTimeout / 2.f);
return true;
}
//-------------------------------------------------------------------------------------
bool Channel::finalise()
{
this->clearState();
SAFE_RELEASE(pPacketReceiver_);
SAFE_RELEASE(pPacketReader_);
SAFE_RELEASE(pPacketSender_);
Network::EndPoint::reclaimPoolObject(pEndPoint_);
pEndPoint_ = NULL;
return true;
}
//-------------------------------------------------------------------------------------
Channel * Channel::get(NetworkInterface & networkInterface,
const Address& addr)
{
return networkInterface.findChannel(addr);
}
//-------------------------------------------------------------------------------------
Channel * get(NetworkInterface & networkInterface,
const EndPoint* pSocket)
{
return networkInterface.findChannel(pSocket->addr());
}
//-------------------------------------------------------------------------------------
void Channel::startInactivityDetection( float period, float checkPeriod )
{
stopInactivityDetection();
// 如果周期为负数则不检查
if(period > 0.001f)
{
checkPeriod = std::max(1.f, checkPeriod);
inactivityExceptionPeriod_ = uint64( period * stampsPerSecond() ) - uint64( 0.05f * stampsPerSecond() );
lastReceivedTime_ = timestamp();
inactivityTimerHandle_ =
this->dispatcher().addTimer( int( checkPeriod * 1000000 ),
this, (void *)TIMEOUT_INACTIVITY_CHECK );
}
}
//-------------------------------------------------------------------------------------
void Channel::stopInactivityDetection()
{
inactivityTimerHandle_.cancel();
}
//-------------------------------------------------------------------------------------
void Channel::pEndPoint(const EndPoint* pEndPoint)
{
if (pEndPoint_ != pEndPoint)
{
Network::EndPoint::reclaimPoolObject(pEndPoint_);
pEndPoint_ = const_cast<EndPoint*>(pEndPoint);
}
lastReceivedTime_ = timestamp();
}
//-------------------------------------------------------------------------------------
void Channel::destroy()
{
if(isDestroyed())
{
CRITICAL_MSG("is channel has Destroyed!\n");
return;
}
clearState();
flags_ |= FLAG_DESTROYED;
}
//-------------------------------------------------------------------------------------
void Channel::clearState( bool warnOnDiscard /*=false*/ )
{
// 清空未处理的接受包缓存
if (bufferedReceives_.size() > 0)
{
BufferedReceives::iterator iter = bufferedReceives_.begin();
int hasDiscard = 0;
for(; iter != bufferedReceives_.end(); ++iter)
{
Packet* pPacket = (*iter);
if(pPacket->length() > 0)
hasDiscard++;
RECLAIM_PACKET(pPacket->isTCPPacket(), pPacket);
}
if (hasDiscard > 0 && warnOnDiscard)
{
WARNING_MSG(fmt::format("Channel::clearState( {} ): "
"Discarding {} buffered packet(s)\n",
this->c_str(), hasDiscard));
}
bufferedReceives_.clear();
}
clearBundle();
lastReceivedTime_ = timestamp();
numPacketsSent_ = 0;
numPacketsReceived_ = 0;
numBytesSent_ = 0;
numBytesReceived_ = 0;
lastTickBytesReceived_ = 0;
proxyID_ = 0;
strextra_ = "";
channelType_ = CHANNEL_NORMAL;
if(pEndPoint_ && protocoltype_ == PROTOCOL_TCP && !this->isDestroyed())
{
this->stopSend();
if(pNetworkInterface_)
{
if(!this->isDestroyed())
pNetworkInterface_->dispatcher().deregisterReadFileDescriptor(*pEndPoint_);
}
}
// 这里只清空状态,不释放
//SAFE_RELEASE(pPacketReader_);
//SAFE_RELEASE(pPacketSender_);
flags_ = 0;
pFilter_ = NULL;
stopInactivityDetection();
// 由于pEndPoint通常由外部给入,必须释放,频道重新激活时会重新赋值
if(pEndPoint_)
{
pEndPoint_->close();
this->pEndPoint(NULL);
}
}
//-------------------------------------------------------------------------------------
Channel::Bundles & Channel::bundles()
{
return bundles_;
}
//-------------------------------------------------------------------------------------
const Channel::Bundles & Channel::bundles() const
{
return bundles_;
}
//-------------------------------------------------------------------------------------
int32 Channel::bundlesLength()
{
int32 len = 0;
Bundles::iterator iter = bundles_.begin();
for(; iter != bundles_.end(); ++iter)
{
len += (*iter)->packetsLength();
}
return len;
}
//-------------------------------------------------------------------------------------
void Channel::delayedSend()
{
this->networkInterface().delayedSend(*this);
}
//-------------------------------------------------------------------------------------
const char * Channel::c_str() const
{
static char dodgyString[ MAX_BUF ] = {"None"};
char tdodgyString[ MAX_BUF ] = {0};
if(pEndPoint_ && !pEndPoint_->addr().isNone())
pEndPoint_->addr().writeToString(tdodgyString, MAX_BUF);
kbe_snprintf(dodgyString, MAX_BUF, "%s/%d/%d/%d", tdodgyString, id_,
this->isCondemn(), this->isDestroyed());
return dodgyString;
}
//-------------------------------------------------------------------------------------
void Channel::clearBundle()
{
Bundles::iterator iter = bundles_.begin();
for(; iter != bundles_.end(); ++iter)
{
Bundle::reclaimPoolObject((*iter));
}
bundles_.clear();
}
//-------------------------------------------------------------------------------------
void Channel::handleTimeout(TimerHandle, void * arg)
{
switch (reinterpret_cast<uintptr>(arg))
{
case TIMEOUT_INACTIVITY_CHECK:
{
if (timestamp() - lastReceivedTime_ >= inactivityExceptionPeriod_)
{
this->networkInterface().onChannelTimeOut(this);
}
break;
}
default:
break;
}
}
//-------------------------------------------------------------------------------------
void Channel::send(Bundle * pBundle)
{
if (isDestroyed())
{
ERROR_MSG(fmt::format("Channel::send({}): channel has destroyed.\n",
this->c_str()));
this->clearBundle();
if(pBundle)
Network::Bundle::reclaimPoolObject(pBundle);
return;
}
if(isCondemn())
{
//WARNING_MSG(fmt::format("Channel::send: is error, reason={}, from {}.\n", reasonToString(REASON_CHANNEL_CONDEMN),
// c_str()));
this->clearBundle();
if(pBundle)
Network::Bundle::reclaimPoolObject(pBundle);
return;
}
if(pBundle)
{
pBundle->finiMessage(true);
bundles_.push_back(pBundle);
}
uint32 bundleSize = (uint32)bundles_.size();
if(bundleSize == 0)
return;
if(!sending())
{
if(pPacketSender_ == NULL)
pPacketSender_ = new TCPPacketSender(*pEndPoint_, *pNetworkInterface_);
pPacketSender_->processSend(this);
// 如果不能立即发送到系统缓冲区,那么交给poller处理
if(bundles_.size() > 0 && !isCondemn() && !isDestroyed())
{
flags_ |= FLAG_SENDING;
pNetworkInterface_->dispatcher().registerWriteFileDescriptor(*pEndPoint_, pPacketSender_);
}
}
if(Network::g_sendWindowMessagesOverflowCritical > 0 && bundleSize > Network::g_sendWindowMessagesOverflowCritical)
{
if(this->isExternal())
{
WARNING_MSG(fmt::format("Channel::send[{:p}]: external channel({}), send-window bufferedMessages has overflowed({} > {}).\n",
(void*)this, this->c_str(), bundleSize, Network::g_sendWindowMessagesOverflowCritical));
if(Network::g_extSendWindowMessagesOverflow > 0 &&
bundleSize > Network::g_extSendWindowMessagesOverflow)
{
ERROR_MSG(fmt::format("Channel::send[{:p}]: external channel({}), send-window bufferedMessages has overflowed({} > {}), Try adjusting the kbengine[_defs].xml->windowOverflow->send.\n",
(void*)this, this->c_str(), bundleSize, Network::g_extSendWindowMessagesOverflow));
this->condemn();
}
}
else
{
if(Network::g_intSendWindowMessagesOverflow > 0 &&
bundleSize > Network::g_intSendWindowMessagesOverflow)
{
ERROR_MSG(fmt::format("Channel::send[{:p}]: internal channel({}), send-window bufferedMessages has overflowed({} > {}).\n",
(void*)this, this->c_str(), bundleSize, Network::g_intSendWindowMessagesOverflow));
this->condemn();
}
else
{
WARNING_MSG(fmt::format("Channel::send[{:p}]: internal channel({}), send-window bufferedMessages has overflowed({} > {}).\n",
(void*)this, this->c_str(), bundleSize, Network::g_sendWindowMessagesOverflowCritical));
}
}
}
}
//-------------------------------------------------------------------------------------
void Channel::stopSend()
{
if(!sending())
return;
flags_ &= ~FLAG_SENDING;
pNetworkInterface_->dispatcher().deregisterWriteFileDescriptor(*pEndPoint_);
}
//-------------------------------------------------------------------------------------
void Channel::onSendCompleted()
{
KBE_ASSERT(bundles_.size() == 0 && sending());
stopSend();
}
//-------------------------------------------------------------------------------------
void Channel::onPacketSent(int bytes, bool sentCompleted)
{
if(sentCompleted)
{
++numPacketsSent_;
++g_numPacketsSent;
}
numBytesSent_ += bytes;
g_numBytesSent += bytes;
lastTickBytesSent_ += bytes;
if(this->isExternal())
{
if(g_extSendWindowBytesOverflow > 0 &&
lastTickBytesSent_ >= g_extSendWindowBytesOverflow)
{
ERROR_MSG(fmt::format("Channel::onPacketSent[{:p}]: external channel({}), bufferedBytes has overflowed({} > {}), Try adjusting the kbengine[_defs].xml->windowOverflow->receive.\n",
(void*)this, this->c_str(), lastTickBytesSent_, g_extSendWindowBytesOverflow));
this->condemn();
}
}
else
{
if(g_intSendWindowBytesOverflow > 0 &&
lastTickBytesSent_ >= g_intSendWindowBytesOverflow)
{
WARNING_MSG(fmt::format("Channel::onPacketSent[{:p}]: internal channel({}), bufferedBytes has overflowed({} > {}).\n",
(void*)this, this->c_str(), lastTickBytesSent_, g_intSendWindowBytesOverflow));
}
}
}
//-------------------------------------------------------------------------------------
void Channel::onPacketReceived(int bytes)
{
lastReceivedTime_ = timestamp();
++numPacketsReceived_;
++g_numPacketsReceived;
numBytesReceived_ += bytes;
lastTickBytesReceived_ += bytes;
g_numBytesReceived += bytes;
if(this->isExternal())
{
if(g_extReceiveWindowBytesOverflow > 0 &&
lastTickBytesReceived_ >= g_extReceiveWindowBytesOverflow)
{
ERROR_MSG(fmt::format("Channel::onPacketReceived[{:p}]: external channel({}), bufferedBytes has overflowed({} > {}), Try adjusting the kbengine[_defs].xml->windowOverflow->receive.\n",
(void*)this, this->c_str(), lastTickBytesReceived_, g_extReceiveWindowBytesOverflow));
this->condemn();
}
}
else
{
if(g_intReceiveWindowBytesOverflow > 0 &&
lastTickBytesReceived_ >= g_intReceiveWindowBytesOverflow)
{
WARNING_MSG(fmt::format("Channel::onPacketReceived[{:p}]: internal channel({}), bufferedBytes has overflowed({} > {}).\n",
(void*)this, this->c_str(), lastTickBytesReceived_, g_intReceiveWindowBytesOverflow));
}
}
}
//-------------------------------------------------------------------------------------
void Channel::addReceiveWindow(Packet* pPacket)
{
bufferedReceives_.push_back(pPacket);
uint32 size = (uint32)bufferedReceives_.size();
if(Network::g_receiveWindowMessagesOverflowCritical > 0 && size > Network::g_receiveWindowMessagesOverflowCritical)
{
if(this->isExternal())
{
if(Network::g_extReceiveWindowMessagesOverflow > 0 &&
size > Network::g_extReceiveWindowMessagesOverflow)
{
ERROR_MSG(fmt::format("Channel::addReceiveWindow[{:p}]: external channel({}), receive window has overflowed({} > {}), Try adjusting the kbengine[_defs].xml->windowOverflow->receive->messages->external.\n",
(void*)this, this->c_str(), size, Network::g_extReceiveWindowMessagesOverflow));
this->condemn();
}
else
{
WARNING_MSG(fmt::format("Channel::addReceiveWindow[{:p}]: external channel({}), receive window has overflowed({} > {}).\n",
(void*)this, this->c_str(), size, Network::g_receiveWindowMessagesOverflowCritical));
}
}
else
{
if(Network::g_intReceiveWindowMessagesOverflow > 0 &&
size > Network::g_intReceiveWindowMessagesOverflow)
{
WARNING_MSG(fmt::format("Channel::addReceiveWindow[{:p}]: internal channel({}), receive window has overflowed({} > {}).\n",
(void*)this, this->c_str(), size, Network::g_intReceiveWindowMessagesOverflow));
}
}
}
}
//-------------------------------------------------------------------------------------
void Channel::condemn()
{
if(isCondemn())
return;
flags_ |= FLAG_CONDEMN;
//WARNING_MSG(fmt::format("Channel::condemn[{:p}]: channel({}).\n", (void*)this, this->c_str()));
}
//-------------------------------------------------------------------------------------
void Channel::handshake()
{
if(hasHandshake())
return;
if(bufferedReceives_.size() > 0)
{
BufferedReceives::iterator packetIter = bufferedReceives_.begin();
Packet* pPacket = (*packetIter);
flags_ |= FLAG_HANDSHAKE;
// 此处判定是否为websocket或者其他协议的握手
if(websocket::WebSocketProtocol::isWebSocketProtocol(pPacket))
{
channelType_ = CHANNEL_WEB;
if(websocket::WebSocketProtocol::handshake(this, pPacket))
{
if(pPacket->length() == 0)
{
bufferedReceives_.erase(packetIter);
}
if(!pPacketReader_ || pPacketReader_->type() != PacketReader::PACKET_READER_TYPE_WEBSOCKET)
{
SAFE_RELEASE(pPacketReader_);
pPacketReader_ = new WebSocketPacketReader(this);
}
pFilter_ = new WebSocketPacketFilter(this);
DEBUG_MSG(fmt::format("Channel::handshake: websocket({}) successfully!\n", this->c_str()));
return;
}
else
{
DEBUG_MSG(fmt::format("Channel::handshake: websocket({}) error!\n", this->c_str()));
}
}
if(!pPacketReader_ || pPacketReader_->type() != PacketReader::PACKET_READER_TYPE_SOCKET)
{
SAFE_RELEASE(pPacketReader_);
pPacketReader_ = new PacketReader(this);
}
pPacketReader_->reset();
}
}
//-------------------------------------------------------------------------------------
void Channel::processPackets(KBEngine::Network::MessageHandlers* pMsgHandlers)
{
lastTickBytesReceived_ = 0;
lastTickBytesSent_ = 0;
if(pMsgHandlers_ != NULL)
{
pMsgHandlers = pMsgHandlers_;
}
if (this->isDestroyed())
{
ERROR_MSG(fmt::format("Channel::processPackets({}): channel[{:p}] is destroyed.\n",
this->c_str(), (void*)this));
return;
}
if(this->isCondemn())
{
ERROR_MSG(fmt::format("Channel::processPackets({}): channel[{:p}] is condemn.\n",
this->c_str(), (void*)this));
//this->destroy();
return;
}
if(!hasHandshake())
{
handshake();
}
try
{
BufferedReceives::iterator packetIter = bufferedReceives_.begin();
for(; packetIter != bufferedReceives_.end(); ++packetIter)
{
Packet* pPacket = (*packetIter);
pPacketReader_->processMessages(pMsgHandlers, pPacket);
RECLAIM_PACKET(pPacket->isTCPPacket(), pPacket);
}
}catch(MemoryStreamException &)
{
Network::MessageHandler* pMsgHandler = pMsgHandlers->find(pPacketReader_->currMsgID());
WARNING_MSG(fmt::format("Channel::processPackets({}): packet invalid. currMsg=(name={}, id={}, len={}), currMsgLen={}\n",
this->c_str()
, (pMsgHandler == NULL ? "unknown" : pMsgHandler->name)
, pPacketReader_->currMsgID()
, (pMsgHandler == NULL ? -1 : pMsgHandler->msgLen)
, pPacketReader_->currMsgLen()));
pPacketReader_->currMsgID(0);
pPacketReader_->currMsgLen(0);
condemn();
}
bufferedReceives_.clear();
}
//-------------------------------------------------------------------------------------
bool Channel::waitSend()
{
return pEndPoint()->waitSend();
}
//-------------------------------------------------------------------------------------
EventDispatcher & Channel::dispatcher()
{
return pNetworkInterface_->dispatcher();
}
//-------------------------------------------------------------------------------------
}
}