iOS 发送 Socket GCD 心跳包

项目中需要发送心跳包给服务端的需求
贴出代码望大神指点

自定义GCD定时函数

#pragma mark - GCD socket心跳事件

/**
 开启一个定时器
 
 @param target 定时器持有者
 @param timeInterval 执行间隔时间
 @param handler 重复执行事件
 */
void dispatchTimer(id target, double timeInterval,void (^handler)(dispatch_source_t timer))
{
    //获取一个低优先级的系统线程队列 DISPATCH_QUEUE_PRIORITY_LOW
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
    dispatch_source_t timer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue);
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), (uint64_t)(timeInterval *NSEC_PER_SEC), 0);
    // 设置回调
    __weak __typeof(target) weaktarget  = target;
    dispatch_source_set_event_handler(timer, ^{
        if (!weaktarget)  {
            dispatch_source_cancel(timer);
        } else {
            
             /*这里是异步的根据业务需求设置主线执行回调
            dispatch_async(dispatch_get_main_queue(), ^{
                    if (handler) handler(timer);
                });
            */
            //异步回调
            if (handler) handler(timer);
        }
    });
    // 启动定时器
    dispatch_resume(timer);
}
///启用串行队列保证线程安全 不然会出现在多个子线程中操作 NSMutableDictionary 的情况
@property (nonatomic, strong) dispatch_queue_t queue;
///发送心跳包需要携带的数据 这个数据是根据服务端协好需要的数据
@property (nonatomic, strong) NSMutableDictionary *heartbeatDic;
//动态添加心跳包所需参数 使用线程同步队列保证线程安全
dispatch_sync(weakSelf.queue, ^(){
   [weakSelf.heartbeatDic setObject:@"value" forKey:@"key"];
 });

在需要启动定时器的地方调用函数

- (void)viewDidLoad {
    __weak typeof(self) weakSelf = self;
    dispatchTimer(self, 5, ^(dispatch_source_t timer) {
       //子线程发送心跳包
       dispatch_sync(weakSelf.queue, ^(){
           if(判断socket是否连接){
                //发送与服务端协同好的socket心跳包事件
            }
        });
     });
}
另外这是一个我觉得还不错的关于GCD博客
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,523评论 25 708
  • 用到的组件 1、通过CocoaPods安装 2、第三方类库安装 3、第三方服务 友盟社会化分享组件 友盟用户反馈 ...
    SunnyLeong阅读 14,709评论 1 180
  • 会继续咯
    denise乔阅读 290评论 0 0
  • 早上刚到站牌,公交车就来了,看看手机,没有时间了,上! 由于到站牌晚,人太多,我就在上车队伍的最后面了。 人实在是...
    琅琊煎饼阅读 316评论 0 1