iOS GCDAsyncSocket 使用

田兴朝
2023-12-01

 

 

相对于原生的 socket,GCDAsyncSocket 封装的很简单,几行代码即可实现。

原生 socket 的实现地址

这里介绍 GCDAsyncSocket 的使用。

 

1、导入

pod 导入 

pod 'CocoaAsyncSocket' ,'~> 7.6.3'

2、头文件及宏

#import <GCDAsyncSocket.h>

#define SocketHost @"172.19.203.106"
#define SocketPort 8081 //端口

3、代理

<GCDAsyncSocketDelegate>

4、连接

- (void)connect
{
    if (self.socket == nil) {
        
        self.socket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
        if (self.socket.isConnected == NO) {
            
            BOOL isSuccess = [self.socket connectToHost:SocketHost onPort:SocketPort error:nil];
            if (!isSuccess) {
                NSLog(@"连接失败");
            }
        }
      
    }
}

5、发送

-(void)send
{
    NSData * data = [@"发送了" dataUsingEncoding:NSUTF8StringEncoding];
    // -1 永不失效
    [self.socket writeData:data withTimeout:-1 tag:1];
    
}

6、关闭

-(void)close
{
    [self.socket disconnect];
    self.socket = nil;
}

7、代理方法

-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"连接成功");
    // -1 永不失效
    [self.socket readDataWithTimeout:-1 tag:1];
}
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"断开连接:%@",err.description);
}
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString * msg = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"接受到消息:%@",msg);
    // -1 永不失效
    [self.socket readDataWithTimeout:-1 tag:1];
}
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"已经发送成功");
}

 

 类似资料: