注冊(cè)了這么久簡(jiǎn)書(shū)賬號(hào)画髓,今天終于決定把自己的總結(jié)發(fā)出來(lái)咨跌。第一篇文章誕生了纲菌!
項(xiàng)目中monitor數(shù)據(jù)上報(bào),消息推送均使用了socket長(zhǎng)連接,技術(shù)上使用GCDAsyncSocket 并做了二次封裝榨汤。
- CocoaAsyncSocket為Mac和iOS提供了易于使用且強(qiáng)大的異步通信庫(kù)滴须。CocoaAsyncSocket是支持tcp和udp的栏笆,利用它可以輕松實(shí)現(xiàn)建立連接屁商、斷開(kāi)連接、發(fā)送socket業(yè)務(wù)請(qǐng)求七问、重連這四個(gè)基本功能蜓耻。
一、GCDAsyncSocket 總結(jié)
在Podfile文件中械巡,只要加上這句話就可以導(dǎo)入了
pod 'CocoaAsyncSocket'
1)首先初始化socket 源碼提供了四種初始化方法
- (instancetype)init;
- (instancetype)initWithSocketQueue:(nullable dispatch_queue_t)sq;
- (instancetype)initWithDelegate:(nullable id<GCDAsyncSocketDelegate>)aDelegate delegateQueue:(nullable dispatch_queue_t)dq;
- (instancetype)initWithDelegate:(nullable id<GCDAsyncSocketDelegate>)aDelegate delegateQueue:(nullable dispatch_queue_t)dq socketQueue:(nullable dispatch_queue_t)sq;
- aDelegate就是socket的代理 dq是delegate的線程
You MUST set a delegate AND delegate dispatch queue before attempting to use the socket, or you will get an error
這里的delegate和dq是必須要有的刹淌。
- sq是socket的線程,這個(gè)是可選的設(shè)置讥耗,如果你寫(xiě)null有勾,GCDAsyncSocket內(nèi)部會(huì)幫你創(chuàng)建一個(gè)它自己的socket線程,如果你要自己提供一個(gè)socket線程的話古程,千萬(wàn)不要提供一個(gè)并發(fā)線程蔼卡,在頻繁socket通信過(guò)程中,可能會(huì)阻塞掉挣磨,個(gè)人建議是不用創(chuàng)建
If you pass NULL, GCDAsyncSocket will automatically create it's own socket queue.
If you choose to provide a socket queue, the socket queue must not be a concurrent queue.
2)初始化socket之后雇逞,需要跟服務(wù)器建立連接
- (BOOL)connectToHost:(NSString *)host onPort:(uint16_t)port error:(NSError **)errPtr;
- host是主機(jī)地址,port是端口號(hào)
如果建連成功之后茁裙,會(huì)收到socket成功的回調(diào)
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port;
如果失敗了塘砸,會(huì)受到以下回調(diào)
- (void)socketDidDisconnect:(GCDAsyncSocket*)sock withError:(NSError*)err
3)發(fā)送數(shù)據(jù)
[self.socket writeData:data withTimeout:-1 tag:0];
發(fā)送數(shù)據(jù)的回調(diào)
- (void)socket:(GCDAsyncSocket*)sock didWriteDataWithTag:(long)tag;
4)讀取數(shù)據(jù)回調(diào)
- (void)socket:(GCDAsyncSocket*)sock didReadData:(NSData*)data withTag:(long)tag晤锥;
5)斷開(kāi)連接掉蔬、重連
[self.socket disconnect];
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
//這里可以做重連操作
}
二.采坑攻略
1)主動(dòng)讀取消息
在發(fā)送消息后,需要主動(dòng)調(diào)取didReadDataWithTimeOut方法讀取消息
矾瘾,這樣才能收到你發(fā)出請(qǐng)求后從服務(wù)器那邊收到的數(shù)據(jù)
- (void)socket:(GCDAsyncSocket*)sock didWriteDataWithTag:(long)tag
{
[self.socket readDataWithTimeout:-1 tag:tag];
}
2)tag 參數(shù)的理解
tag 參數(shù),乍一看可能會(huì)以為在writeData到readData一次傳輸過(guò)程中保持一致女轿。看似結(jié)果是這樣壕翩,但是tag參數(shù)并沒(méi)有加在數(shù)據(jù)傳輸中蛉迹。
tag 是為了在回調(diào)方法中匹配發(fā)起調(diào)用的方法的,不會(huì)加在傳輸數(shù)據(jù)中戈泼。
調(diào)用write方法婿禽,收到didWriteData 回調(diào) 調(diào)用writeDataWithTimeOut 讀取數(shù)據(jù)赏僧。收到消息后大猛,會(huì)回調(diào)didReadData的delegate方法扭倾。這是一次數(shù)據(jù)發(fā)送,在接受服務(wù)端回應(yīng)的過(guò)程挽绩。
- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag;
writeData方法中的tag 和 DidWriteData代理回調(diào)中的tag是對(duì)應(yīng)的膛壹。源碼中tag的傳遞是包含在當(dāng)前寫(xiě)的數(shù)據(jù)包 GCDAsyncWritePacket currentWrite 中。
同理
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
readData 方法中的tag 和 readDataWithTimeout 代理回調(diào)中的tag是一致的
tag 傳遞包含在GCDAsyncReadPacket * currentRead 數(shù)據(jù)包中唉堪。
需要注意:根據(jù)tag做消息回執(zhí)的標(biāo)識(shí)模聋,可能會(huì)出現(xiàn)錯(cuò)亂的問(wèn)題
以read為例分析:
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;
上面的方法會(huì)生成一個(gè)數(shù)據(jù)類:AsyncReadPacket,此類中包含tag唠亚,并把此對(duì)象放入數(shù)組 readQueue中链方。
(先進(jìn)先出,比如read了了三次灶搜,分別為1祟蚀,2,3割卖,那么回調(diào)的tag會(huì)依次是1前酿,2,3)
在CFStream中的回調(diào)方法中鹏溯,會(huì)取readQueue最新的一個(gè)罢维,在回調(diào)方法中取得tag,并將tag傳給回調(diào)方法:
- (void)onSocket:(AsyncSocket *)sock didReadData:(long)tag;
這樣看似tag 傳遞了下去丙挽。但是看下面的讀取數(shù)據(jù)部分源碼:
//用偏移量 maxLength 讀取數(shù)據(jù)
- (void)readDataWithTimeout:(NSTimeInterval)timeout
buffer:(NSMutableData *)buffer
bufferOffset:(NSUInteger)offset
maxLength:(NSUInteger)length
tag:(long)tag
{
if (offset > [buffer length]) {
LogWarn(@"Cannot read: offset > [buffer length]");
return;
}
GCDAsyncReadPacket *packet = [[GCDAsyncReadPacket alloc] initWithData:buffer
startOffset:offset
maxLength:length
timeout:timeout
readLength:0
terminator:nil
tag:tag];
dispatch_async(socketQueue, ^{ @autoreleasepool {
LogTrace();
if ((flags & kSocketStarted) && !(flags & kForbidReadsWrites))
{
//往讀的隊(duì)列添加任務(wù)肺孵,任務(wù)是包的形式
[readQueue addObject:packet];
[self maybeDequeueRead];
}
}});
// Do not rely on the block being run in order to release the packet,
// as the queue might get released without the block completing.
}
讀取數(shù)據(jù)時(shí)的packet實(shí)際是是根據(jù)readDataWithTimeOut方法傳進(jìn)來(lái)的tag重新alloc出來(lái)的消息,假如服務(wù)端回執(zhí)消息異常,相同tag對(duì)應(yīng)的消息回執(zhí)就會(huì)不匹配颜阐。這一點(diǎn)需要注意悬槽。實(shí)際業(yè)務(wù)中,上報(bào)消息后會(huì)根據(jù)服務(wù)端的回執(zhí)消息做邏輯處理瞬浓,倘若回執(zhí)消息丟失初婆,根據(jù)tag匹配到消息回執(zhí)就會(huì)造成錯(cuò)亂。
官方解釋
In addition to this you've probably noticed the tag parameter. The tag you pass during the read/write operation is passed back to you via the delegate method once the read/write operation completes. It does not get sent over the socket or read from the socket. It is designed to help simplify the code in your delegate method. For example, your delegate method might look like this:
#define TAG_WELCOME 10
#define TAG_CAPABILITIES 11
#define TAG_MSG 12
...
- (void)socket:(AsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag
{
if (tag == TAG_WELCOME)
{
// Ignore welcome message
}
else if (tag == TAG_CAPABILITIES)
{
[self processCapabilities:data];
}
else if (tag == TAG_MSG)
{
[self processMessage:data];
}
}