不成熟的iOS socket 连接服务

本文介绍了一个使用GCDAsyncSocket库实现的TCP客户端API。该API实现了连接服务器、发送数据及接收服务器响应等功能,并提供了详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


//
//  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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值