美文网首页
iOS 发送 Socket GCD 心跳包

iOS 发送 Socket GCD 心跳包

作者: 我们只是GitHub的搬运工 | 来源:发表于2018-04-15 00:25 被阅读825次
项目中需要发送心跳包给服务端的需求
贴出代码望大神指点

自定义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博客

相关文章

  • iOS 发送 Socket GCD 心跳包

    项目中需要发送心跳包给服务端的需求 贴出代码望大神指点 自定义GCD定时函数 在需要启动定时器的地方调用函数 另外...

  • iOS学习之Socket使用简明教程- AsyncSocket

    一、摘要ios socket第三方框架 AsyncSocket使用简介,连接,心跳,断线,数据发送与接收 ios原...

  • socket通信

    连接socket成功后 就发送心跳包 用一个NSTimer定时器 每隔15秒 发送一次 如果 检测到 当前时间...

  • Socket--AsycnSocket

    摘要ios socket第三方框架 AsyncSocket使用简介,连接,心跳,断线,数据发送与接收 如果需要在项...

  • 直播项目笔记(四)

    心跳包 + 图文混排 + Core Graphics Socket 服务器加入心跳包 Timer 和 Runloo...

  • 长连接和心跳

    长连接实现的几种方式 socket建立长连接并发送心跳

  • Java Udp网络编程

    1、指定socket端口2、在发送的包中指定发送到的地址和端口3、发送的包中的端口必须和接受端的socket端口相同

  • 即时通讯

    iOS即时通讯,从入门到“放弃”?socket的半包,粘包与分包的问题iOS 处理socket粘包问题iOS___...

  • python socket发送魔法包网络唤醒开机.py

    python socket发送魔法包网络唤醒开机.py

  • Socket心跳包机制与实现

    心跳包的发送,通常有两种技术 方法1:应用层自己实现的心跳包 由应用程序自己发送心跳包来检测连接是否正常,大致的方...

网友评论

      本文标题:iOS 发送 Socket GCD 心跳包

      本文链接:https://www.haomeiwen.com/subject/fsbrkftx.html