CocoaAsyncSocket 使用

2020-09-13  本文已影响0人  copy_farmer

1.**CocoaAsyncSocket介绍 **

CocoaAsyncSocket 是适用于 Mac 和 iOS 的异步套接字网络库,支持 tcp 和 udp。其中:
AsyncSocket 类是支持TCP的
AsyncUdpSocket 是支持UDP的

2.**本地集成CocoaAsyncSocket **

下载通道

3.pod集成

  pod 'CocoaAsyncSocket'

4.代码

HGFCTCPSocketServe.h

#import <Foundation/Foundation.h>
#import <GCDAsyncSocket.h>



@interface HGFCTCPSocketServe : NSObject <GCDAsyncSocketDelegate>
{
    GCDAsyncSocket *_asyncSocket;
    int reConnectCount;
    
    dispatch_source_t _connectTimer;
    dispatch_queue_t _connectQueue;
    BOOL connectInterrupt;
    
}

+ (instancetype)sharedInstance;

@property(nonatomic,copy) NSString * connectStatusStr;    //打印连接状态




/** 是否连接 */
- (BOOL)isFCDisConnect;

@property (nonatomic, assign) BOOL isFCConnect;

- (void)writeToFCTCPWithData:(NSData *)data;
/**
 * 开启HGFCTCPSocketServe
 */
-(void)start;
/**
 * 关闭HGFCTCPSocketServe
 */
-(void)stop;

- (void)disconnect;

@end

HGFCTCPSocketServe.m

#import <UIKit/UIKit.h>
#import "HGFCTCPSocketServe.h"

#define kTcpFCPort  5000
#define kTCPIP @"192.168.1.1"
@interface HGFCTCPSocketServe ()
@end

@implementation HGFCTCPSocketServe
static HGFCTCPSocketServe *hgFcTcpsocket = nil;
static dispatch_once_t onceToken;
+ (instancetype)sharedInstance {
    dispatch_once(&onceToken, ^{
        hgFcTcpsocket = [[self alloc] init];
    });
    return hgFcTcpsocket;
}//初始化
- (instancetype)init
{
    if (self = [super init]) {
        _asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        hgFCConnectTool=[HGFCConnectTool sharedInstance];
        
  
    }
    return self;
}
/**
 * 开启HGFCTCPSocketServe
 */
-(void)start{
    reConnectCount=0;
    [self connectWithHost:kTCPIP port:kTcpFCPort];
    
}
/**
 * 关闭HGFCTCPSocketServe
 */
-(void)stop{

    if(_connectTimer!=nil)
    {
        dispatch_source_cancel(_connectTimer);
        _connectTimer = nil;
    }
    [self disconnect];
    
}

//连接socket 地址 端口号
- (void)connectWithHost:(NSString *)hostName port:(int)port
{
    NSError *error = nil;
    if ([self isFCDisConnect])
    {
        [_asyncSocket connectToHost:hostName onPort:port withTimeout:4.0 error:&error];
        NSLog(@"%@",[NSString stringWithFormat:@"开始连接:%d",port]);
    }
    if (error) {
         NSLog(@"%@",[NSString stringWithFormat:@"5000连接错误:%@",error]);
   
            [self reConnect];
     
    }
}
//断开连接
- (void)disconnect
{
    [_asyncSocket disconnect];
}

//是否连接
- (BOOL)isFCDisConnect
{
    return [_asyncSocket isDisconnected];
}

//读
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag
{
    [_asyncSocket readDataWithTimeout:-1 tag:tag];
}

//写
- (void)writeToFCTCPWithData:(NSData *)data;
{
 
    [_asyncSocket writeData:data withTimeout:-1 tag:kTcpFCPort];
    
}

#pragma mark GCDAsyncSocketDelegate method
//断开连接代理
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"5000 断开");


     reConnectCount++;
       [self reConnect];
   
}
//连接成功代理
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {

    NSLog(@"5000 端口连接成功");

    if(_connectTimer!=nil)
    {
        dispatch_source_cancel(_connectTimer);
        _connectTimer = nil;
    }
    
    
    [sock readDataWithTimeout:-1 tag:kTcpFCPort];
}

//读数据成功代理
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {

    
    [sock readDataWithTimeout:-1 tag:tag];
}
///发送消息成功之后回调
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {
    
    [sock readDataWithTimeout:-1 tag:kTcpFCPort];
}

//断开重连方法
-(void)fcConnectTimerStart{
   
    @autoreleasepool {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"5000 重新连接");
            [self connectWithHost:kTCPIP port:kTcpFCPort];
        });
    }
}


//重连线程
-(void)reConnect{
    if(_connectTimer!=nil)
    {
        dispatch_source_cancel(_connectTimer);
        _connectTimer = nil;
    }
    if(reConnectCount>6){
        reConnectCount=6;
    }
    
    _connectQueue = dispatch_queue_create("_reConnectFCQueue", NULL);
    _connectTimer= dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _connectQueue);
    //开始时间
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC);
    //间隔时间
    uint64_t interval = NSEC_PER_SEC * reConnectCount;
    dispatch_source_set_timer(_connectTimer, start, interval, 0);
    //设置回调
    __weak __typeof__(self) weakSelf = self;
    dispatch_source_set_event_handler(_connectTimer, ^{
        [weakSelf fcConnectTimerStart];
    });
    //启动timer
    dispatch_resume(_connectTimer);
}

-(void)Dealloc
{
    [_asyncSocket disconnect];
    _asyncSocket.delegate=nil;
    _asyncSocket=nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"Dealloc  hgfctcpsocket");
    hgFcTcpsocket=nil;
    onceToken=0;
}
上一篇下一篇

猜你喜欢

热点阅读