AsyncSocket中tag参数的用处

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值