1. 程式人生 > >不成熟的iOS socket 連線服務

不成熟的iOS socket 連線服務

//
//  TcpClientAPI.m
//  test_GCDAsyncSocket_01
//
//  Created by jeffasd on 16/9/6.
//  Copyright © 2016年 jeffasd. All rights reserved.
//

#import "TcpClientAPI.h"
#import "GCDAsyncSocket.h"

@interface TcpClientAPI () <GCDAsyncSocketDelegate>
{
    dispatch_queue_t globalQueue;
}

@property (nonatomic, strong)GCDAsyncSocket *gcdAsyncSocket;

@end

@implementation TcpClientAPI

+ (instancetype)shareTcpClientAPI{
    
    static TcpClientAPI *_sharedInstance = nil;
    
    if (_sharedInstance == nil) {

        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _sharedInstance = [[TcpClientAPI alloc] init];
        });
    }

    return _sharedInstance;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
        self.gcdAsyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:globalQueue];
        [self.gcdAsyncSocket setAutoDisconnectOnClosedReadStream:NO];
    }
    
    return self;
    
}

/** 連線伺服器 */
- (void)openTcpConnection:(NSString *)host port:(NSUInteger)port{
    
    NSError *error = nil;
    BOOL isSuccess = [self.gcdAsyncSocket connectToHost:host onPort:port error:&error];
    
    if (isSuccess && error == nil) {
        
    }else{
        NSLog(@"the error is %@", error);
    }
}


#pragma mark - GCDSocket delegate
#pragma mark - 連線主機成功
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    
    NSLog(@"連線主機成功");
}

#pragma mark - 與主機斷開連線
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    NSLog(@"斷開連線 error is %@", err);
}

#pragma mark - 資料成功傳送到伺服器
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    
    NSLog(@"資料成功傳送到伺服器");
    
    //資料傳送成功後需要自己呼叫讀取函式 資料才會呼叫資料讀取代理
    [_gcdAsyncSocket readDataWithTimeout:-1 tag:tag];
}

#pragma mark - 伺服器返回有資料,會呼叫這個方法
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    
    //從伺服器接受資料
    NSString *receiveStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"the receiveStr is %@", receiveStr);
}

@end