GCDAsyncSocket.

来源:互联网 发布:淘宝没销量怎么办 编辑:程序博客网 时间:2024/05/18 21:43

1.这是TCP的使用的Socket包,无论怎么样都要先connect.

-(void)socketConnectHost{​

    if (_socket == nil) {

        dispatch_queue_t mainQueue = dispatch_get_main_queue();

        _socket = [[GCDAsyncSocketallocinitWithDelegate:selfdelegateQueue:mainQueue];

        NSError *err = nil;

        [selfconnectToHost:kConf_Server_AddrandPort:kConf_Server_PORT];

        if(![_socketconnectToHost:kConf_Server_Addr  onPort:kConf_Server_PORTerror:&err])

        {

            NSLog(@"Error: %@", err);

        }

    }else{

        [selfconnectToHost:kConf_Server_AddrandPort:kConf_Server_PORT];

    }

 }

只有- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{}成功之后,才能收发socket.

收socket:- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{}

发socket: [_socketwriteData:data withTimeout:-1tag:1];

断开连接会调用:- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{}

当然一般情况下我们在socket断开时要重连.重连时间,一般是服务器和客户端商量好的.在断开之后,在:- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{}使用NSTimer设置重连,重连成功,停止timer.

2.当我们要在后台接收socket时,可以在targets->capabilities->background modes->Voice Over Ip 打开VOIP.

(1),可以

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port

{

    //后台挂起voip

    [asyncSocket performBlock:^{

        [asyncSocket enableBackgroundingOnSocket];

    }];

}

(2),也可以在appdelegate.m里面设置

- (void)applicationDidEnterBackground:(UIApplication *)application{

    UIApplication *app = [UIApplication sharedApplication];

    __block UIBackgroundTaskIdentifier bgTask;

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{

    dispatch_async(dispatch_get_main_queue(),^{

            if(bgTask != UIBackgroundTaskInvalid){

                bgTask = UIBackgroundTaskInvalid;

            }

             });

        }];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,  0),^{

            dispatch_async(dispatch_get_main_queue(), ^{

               if(bgTask != UIBackgroundTaskInvalid)  {

                    bgTask = UIBackgroundTaskInvalid; }

                });

      });

    

}


0 0
原创粉丝点击