zoukankan      html  css  js  c++  java
  • 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];
        }

  • 相关阅读:
    流的概念(转自本站progor)
    Centos7安装OpenLDAP
    python发送post请求
    小计安装部署滴滴开源kafkamanager工具
    VSCode集成Cmder控制台输入中文乱码
    在win10的pycharm使用wsl中的python进行开发
    《Python数据科学手册》学习笔记及书评
    VSCode小说插件ReadNovel根据内容查找页码
    《TensorFlow实战Google深度学习框架(第二版)》学习笔记及书评
    Cmder启动WSL中的Ubuntu出现复制粘贴异常
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7200236.html
Copyright © 2011-2022 走看看