There are actually two classes inside the CocoaAsyncSocket framework, a TCP-based GCDAsyncSocket and a UDP-based GCDAsyncUdpSocket, which help us encapsulate a lot of code.Implements clients to connect to the server to receive and receive data.

First let's connect

- (void)connectToHost{
    // 1. Set the host address and port number first
    NSString *host = @"";
    int port = 8787;
    // 2. Create a Socket Object
    _socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    //3. Connection
    NSError *error = nil;
    [_socket connectToHost:host onPort:port error:&error];
    if (error) {
Next we go to implement the GCDAsyncSocketDelegate proxy method

When the connection is successfully established, the following method is called

-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    NSLog(@"Connection Successful");
The following method is called when disconnecting from the host

-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{

        NSLog(@"Disconnect %@",err);
Send data out, where tag actually serves as an identifier, -1 means infinity or no timeout

 [_socket writeData:data withTimeout:-1 tag:101];

When the data is successfully sent, the following method is called

-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    NSLog(@"Data successfully sent to server");
    //After the data is sent successfully, call the method of reading the data yourself
    [_socket readDataWithTimeout:-1 tag:tag];
It is important to note that the task is marked as completed only if we call one of the following three methods

- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;
- (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag;
- (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
To call the following method

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