GCDAsyncSocket-ios

胡飞鹏
2023-12-01

@property (nonatomic, strong) GCDAsyncSocket *socket;

连接


        //连接上
        [self.socket setDelegate:nil];
        [self.socket disconnect];
        self.socket=nil;
        self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        NSError *error = nil;
        //发起连接
        [self.socket connectToHost:socketPath1 onPort:[socketPathPort longLongValue] withTimeout:-1 error:&error];
        
        [_socket readDataWithTimeout:-1 tag:0];
        

判断是否连接成功

- (BOOL)connectToHost:(NSString *)host
               onPort:(uint16_t)port
          withTimeout:(NSTimeInterval)timeout
                error:(NSError **)errPtr;

连接上

//链接上
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
//host是主机地址,port是端口号
    NSLog(@"报警器socket已连接上=======");
//这里可以写入发起心跳
    
}

连接失败

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
//在这里写入连接服务器失败的操作
}

socket协议格式,比如:

[NSString stringWithFormat:@"{\"version\":%d,\"reqType\":%d,\"body\":\"%@\"}\r\n",PROTOCOL_VERSION,reqType,reqBody];

发起写入 和读取

Byte byte[] = {0x30,0x30};
    NSData *adata = [NSData dataWithBytes:byte length:sizeof(byte)];
    [_socket writeData:adata withTimeout:-1 tag:0];//写
    [_socket readDataWithTimeout:-1 tag:0];//读取数据

写入回调

- (void)socket:(GCDAsyncSocket*)sock didWriteDataWithTag:(long)tag{

}

读取回调

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

}

断开连接

[self.socket disconnect];
 类似资料: