1. 程式人生 > >AsyncSocket中tag參數的用處

AsyncSocket中tag參數的用處

fin pos cfs long it is param ati nor pac

tag參數是為了在回調方法中匹配發起調用的方法的,不會加在數據傳輸中。


調用write方法,等待接收消息。收到消息後,會回調didReadData的delegate方法,
delegate方法中的tag和發起read的方法中的tag是相應的。
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;


write和read是一樣:writeData方法和相應的delegate方法didWriteDataWithTag的tag是相應的。
- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag;


需註意的一點是:發送時的tag和接收時的tag是無關的。


以read為例分析:
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag
上面的方法會生成一個數據類:AsyncReadPacket,此類中包括tag,並把此對象放入數組theReadQueue中。


在CFStream中的回調方法中,會取theReadQueue最新的一個,在回調方法中取得tag,並將tag傳
給回調方法:
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag;
如此而已。




官方解釋:


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];
}

AsyncSocket中tag參數的用處