The original link

The basic concept

Network processes communicate through sockets, so what is a socket?

  1. A socket is a mechanism provided for network services. Both ends of communication are sockets. Network communication is actually communication between sockets. Data is transmitted between two sockets through IO.

  2. Data is used to describe the IP address and port in the two sockets. It is the handle of the communication chain. Applications can send or reply network requests through the Socket. It is the basic operation unit of network communication supporting TCP/IP protocol. It is the abstract representation of the endpoint in the process of network communication. The packet contains five kinds of information necessary for communication: connection protocol, local host IP, local remote protocol port, remote host IP, remote process protocol port.

  3. Socket can actively send requests, so it is fast and saves bandwidth, and has timeliness, so it is widely used in IM.

Correlation function

Socket originated from Unix, and one of the basic philosophies of Unix/Linux is that “everything is a file”, which can be operated in “open – > read/write/read – > Close” mode.

And Socket is an implementation of this mode, Socket is a special file, some Socket functions are operations on it (read/write IO, open, close).

  • The socket function

Corresponds to the open operation of a normal file. Normal file opening operations return a file descriptor, while socket() is used to create a socket descriptor that uniquely identifies a socket. The socket descriptor, like the file descriptor, is used for subsequent operations. It is used as a parameter to perform some read and write operations.

  • The bind () function

Assigns a specific address in an address family to the socket. For example, AF_INET and AF_INET6 assign an ipv4 or ipv6 address and port number to the socket.

  • Listen (), connect() functions

The first argument to listen is the socket description to listen on, and the second argument is the maximum number of connections that the socket can queue. The socket() function creates a socket of an active type by default. The Listen function changes the socket to a passive type, waiting for a connection request.

The first argument to connect is the client’s socket description, the second argument is the server’s socket address, and the third argument is the length of the socket address. The client establishes a connection to the TCP server by calling the connect function

  • Functions such as read() and write()

After the server and the customer have established a good connection, you can call the network I/O for reading and writing operations, that is, to achieve the communication between different processes in the network role!

  • Close () function

After the connection between the server and the client is established, some read and write operations will be carried out. After the read and write operations are completed, the corresponding socket description word should be closed. For example, after the operation, the opened file should be closed by calling fclose.

The Socket location

Socket is the intermediate software abstraction layer of communication between application layer and TCP/IP protocol family. It is a group of interfaces.

GCDAsySocket

Socket is a pure C language Api, is cross-platform, so the project practice is more the third library GCDAsySocket

Create links

// Create socket if (self.socket == nil) // concurrent queue self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)]; // connect socket if (! self.socket.isConnected){ NSError *error; [self.socket connectToHost:@"127.0.0.1" onPort:8090 withTimeout:-1 error:&error]; [self.socket connectToHost:@"127.0.0.1" onPort:8090 withTimeout:-1 error:&error] if (error) NSLog(@"%@",error); }Copy the code

To send data

    NSData *data = [self.contentTF.text dataUsingEncoding:NSUTF8StringEncoding];
    [self.socket writeData:data withTimeout:-1 tag:10086];

Copy the code

reconnection

// Create socket if (self.socket == nil) self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)]; // connect socket if (! self.socket.isConnected){ NSError *error; [self.socket connectToHost:@"127.0.0.1" onPort:8090 withTimeout:-1 error:&error]; [self.socket connectToHost:@"127.0.0.1" onPort:8090 withTimeout:-1 error:&error] if (error) NSLog(@"%@",error); }Copy the code

Shut down

 [self.socket disconnect];
 self.socket = nil;
Copy the code

Agent – GCDAsyncSocketDelegate

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(nonnull NSString *)host port:(uint16_t)port{ NSLog(@" connection successful: %@-- %d",host,port); [self.socket readDataWithTimeout:-1 tag:10086]; } // Connection is disconnected - (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{NSLog(@" Socket connection is disconnected because :%@",err); } - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{NSLog(@" received tag = %ld: %ld length data ",tag,data.length); [self.socket readDataWithTimeout:-1 tag:10086]; } - (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{NSLog(@"%ld send data successfully ",tag);  }Copy the code