Introduction to HTTP, TCP/IP, and Socket

The first thing we need to know is that Socket is a calling interface (API) that encapsulates the TCP/IP protocol. Through Socket, we can use the TCP/IP protocol. This article mainly introduces the TCP/IP protocol, Socket principle and the use of Socket in the iOS development process.

In order to have a deeper understanding of Socket, let's first take a closer look at what the TCP/IP protocol is:

1. Introduction to TCP/IP protocol

The TCP/IP protocol is a protocol suite. It includes many agreements. UDP is just one of them. The reason why it is named TCP/IP protocol is because TCP and IP protocols are two very important protocols, so they were named after them. The TCP/IP protocol set includes the network interface layer, network layer, transport layer, and application layer.

1.1. Network interface layer

The network interface layer is also called the host-to-network layer (host-to-network). The functions of the network interface layer include the mapping of IP addresses and physical address hardware, and the encapsulation of IP into frames, network interfaces based on different hardware types, and network access. Layers define connections to physical media.

The physical layer defines various characteristics of the physical medium: mechanical characteristics, electronic characteristics, functional characteristics, and procedural characteristics.

The data link layer is responsible for receiving IP data packets and sending them through the network, or receiving physical frames from the network, extracting IP data packets, and passing them to the IP layer.

ARP is a forward address resolution protocol that uses a known IP to find the MAC address of the corresponding host.
RARP is the Reverse Address Resolution Protocol, which determines the IP address through the MAC address. For example, diskless workstations also have DHCP services.

Common interface layer protocols include: Ethernet 802.3, Token Ring 802.5, X.25, Frame relay, HDLC, PPP ATM, etc.

1.2. Network layer

The network layer is responsible for communication between adjacent computers. Its function includes three aspects.

1、处理来自传输层的分组发送请求,收到请求后,将分组装入IP数据报,填充报头,选择去往信宿机的路径,然后将数据报发往适当的网络接口。

2、处理输入数据报:首先检查其合法性,然后进行寻径--假如该数据报已到达信宿机,则去掉报头,将剩下部分交给适当的传输协议;假如该数据报尚未到达信宿,则转发该数据报。

3、处理路径、流控、拥塞等问题。

The network layer includes: IP (Internet Protocol) protocol, ICMP (Internet Control Message Protocol) control message protocol, ARP (Address Resolution Protocol) address translation protocol, RARP (Reverse ARP) reverse address translation protocol.

IP is the core of the network layer. The next IP is encapsulated through routing and handed over to the interface layer. IP datagrams are connectionless services.
ICMP is a supplement to the network layer and can send back messages. Used to check whether the network is unobstructed.

The Ping command is to send an ICMP echo packet, and perform a network test through the echo relay sent back.

1.3. Transport layer

The transport layer provides communication between applications. Its functions include: formatting information flow and providing reliable transmission.

The transport layer protocols are mainly: Transmission Control Protocol (TCP) and User Datagram Protocol (UDP).

Some basic knowledge of TCP includes: three-way handshake and four-time disconnection. TCP uses a connection-oriented communication method, which greatly improves the reliability of data communication, allowing the sending data end and the receiving end to interact before the data is officially transmitted. , laying a reliable foundation for formal data transmission

The following is a brief introduction to TCP's three-way handshake, four-way disconnection and UDP:

1.3.1, TCP three-way handshake process and characteristics

Three-way handshake process:

1 主机A通过向主机B 发送一个含有同步序列号的标志位的数据段给主机B ,向主机B 请求建立连接,通过这个数据段,主机A告诉主机B两件事:我想要和你通信;你可以用哪个序列号作为起始数据段来回应我.

2 主机B 收到主机A的请求后,用一个带有确认应答(ACK)和同步序列号(SYN)标志位的数据段响应主机A,也告诉主机A两件事:我已经收到你的请求了,你可以传输数据了;你要用哪佧序列号作为起始数据段来回应我

3 主机A收到这个数据段后,再发送一个确认应答,确认已收到主机B 的数据段:"我已收到回复,我现在要开始传输实际数据了

这样3次握手就完成了,主机A和主机B 就可以传输数据了.

Characteristics of the three-way handshake:

1、没有应用层的数据
2、SYN这个标志位只有在TCP建产连接时才会被置1
3、握手完成后SYN标志位被置0

1.3.2, TCP four disconnection process

1. After host A completes the data transmission, it sets the control bit FIN to 1 and makes a request to stop the TCP connection.

2. Host B responds to the FIN after receiving it, confirms that the TCP connection in this direction will be closed, and sets ACK to 1

3. The B side makes a shutdown request in the opposite direction and sets FIN to 1.

4. Host A confirms Host B’s request, sets ACK to 1, and the two-way shutdown ends.

ACK: One of the control bits in the TCP header, which confirms the data. The acknowledgment is sent by the destination, and is used to tell the sending end that the data segments before the sequence number have been received. For example, if the acknowledgment number is X, it means that the previous X- 1 data segment has been received. Only when ACK=1, the confirmation number is valid. When ACK=0, the confirmation number is invalid. At this time, the data will be required to be retransmitted to ensure the integrity of the data.

SYN: Synchronization sequence number, this bit is set to 1 when TCP establishes a connection

FIN: The sender has completed the sending task bit. When TCP completes the data transmission and needs to be disconnected, the party that proposes to disconnect will set this bit to 1

1.3.3, UDP (User Data Protocol, User Datagram Protocol)

1. UDP is a connectionless protocol. The source and terminal do not establish a connection before transmitting data. When it wants to transmit, it simply grabs the data from the application and throws it on the network as quickly as possible. On the sending end, the speed at which UDP transmits data is only limited by the speed at which the application generates data, the computer's capabilities, and the transmission bandwidth; at the receiving end, UDP puts each message segment in a queue, and the application reads each message segment from the queue each time. Read a message segment.

2. Since no connection is established when transmitting data, there is no need to maintain the connection status, including sending and receiving status, etc. Therefore, a server machine can transmit the same message to multiple clients at the same time.

3. The header of the UDP packet is very short, only 8 bytes, and the additional overhead compared to the 20-byte packet of TCP is very small.

4. Throughput is not regulated by the congestion control algorithm and is only limited by the rate of data generated by the application software, transmission bandwidth, and source and terminal host performance.

5. UDP uses best-effort delivery, that is, reliable delivery is not guaranteed, so the host does not need to maintain a complex link state table (there are many parameters in it).

6. UDP is packet-oriented. The sender's UDP sends the message to the application program, and after adding the header, it is delivered to the IP layer. The boundaries of these packets are neither split nor merged, but the boundaries of these packets are preserved, so the application needs to choose an appropriate packet size.

We often use the "ping" command to test whether the TCP/IP communication between two hosts is normal. In fact, the principle of the "ping" command is to send a UDP data packet to the other host, and then the other host confirms receipt of the data packet. If the data packet is If the incoming news is fed back in time, then the network is connected.

1.4. Application layer

The application layer provides users with a set of commonly used applications, such as email, file transfer access, remote login, etc. Remote login TELNET uses the TELNET protocol to provide an interface for registration on other hosts on the network. TELNET sessions provide a character-based virtual terminal. File transfer access FTP uses the FTP protocol to provide file copy functions between machines within the network.

Application layer protocols mainly include the following: FTP, TELNET, DNS, SMTP, NFS, HTTP.

FTP (File Transfer Protocol) is a file transfer protocol. Generally, FTP service is used for uploading and downloading. The data port is 20H, and the control port is 21H.
Telnet service is a remote login service for users. It uses port 23H and uses clear code to transmit. It has poor confidentiality and is simple and convenient.
DNS (Domain Name Service) is a domain name resolution service that provides conversion between domain names and IP addresses, using port 53.
SMTP (Simple Mail Transfer Protocol) is a simple mail transfer protocol, used to control the sending and transfer of letters, using port 25.
NFS (Network File System) is a network file system used for file sharing between different hosts on the network.
HTTP (Hypertext Transfer Protocol) is a hypertext transfer protocol, used to implement WWW services on the Internet, using port 80.

1.4.1. HTTP connection

The HTTP protocol, namely the Hypertext Transfer Protocol (HypertextTransferProtocol), is the basis of Web networking and one of the commonly used protocols for mobile phone networking. The HTTP protocol is an application built on top of the TCP protocol.

The most notable feature of the HTTP connection is that each request sent by the client requires the server to send back a response, and the connection will be released actively after the request ends. The process from establishing a connection to closing the connection is called "a connection".

1、在HTTP 1.0中,客户端的每次请求都要求建立一次单独的连接,在处理完本次请求后,就自动释放连接。

2、在HTTP 1.1中则可以在一次连接中处理多个请求,并且多个请求可以重叠进行,不需要等待一个请求结束后再发送下一个请求。

Since HTTP will actively release the connection after each request ends, the HTTP connection is a "short connection". To keep the client program online, it is necessary to continuously initiate connection requests to the server. General

The method is that there is no need to obtain any data, and the client keeps sending a "keep connected" request to the server at regular intervals. After receiving the request, the server replies to the client, indicating that it knows that the client is "online" . If the server cannot receive the client's request for a long time, the client is considered "offline". If the client cannot receive the server's reply for a long time, the network is considered disconnected.

2. Introduction to SOCKET principles

2.1, socket (socket) concept

Socket is the cornerstone of communication and the basic operation unit of network communication supporting TCP/IP protocol. It is an abstract representation of the endpoint in the network communication process and contains five types of information necessary for network communication: the protocol used for connection, the IP address of the local host, the protocol port of the local process, the IP address of the remote host, and the protocol of the remote process. port.

When the application layer communicates data through the transport layer, TCP will encounter the problem of providing concurrent services to multiple application processes at the same time. Multiple TCP connections or multiple application processes may need to transmit data through the same TCP protocol port. In order to distinguish different application processes and connections, many computer operating systems provide socket (Socket) interfaces for applications to interact with the TCP/IP protocol. The application layer can use the Socket interface with the transport layer to distinguish communications from different application processes or network connections to implement concurrent services for data transmission.

2.2. Establish socket connection

Establishing a Socket connection requires at least one pair of sockets, one of which runs on the client side, called ClientSocket, and the other runs on the server side, called ServerSocket.

The connection process between sockets is divided into three steps: server monitoring, client request, and connection confirmation.

Server monitoring: The server-side socket does not locate the specific client socket, but is in the state of waiting for connection, monitors the network status in real time, and waits for the connection request of the client.

Client request: Refers to the client's socket making a connection request, and the target to be connected is the server's socket. To do this, the client's socket must first describe the server's socket to which it wants to connect, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket.

Connection confirmation: When the server-side socket listens or receives a connection request from the client socket, it responds to the client socket's request, establishes a new thread, and sends the description of the server-side socket. To the client, once the client confirms this description, the two parties formally establish the connection. The server-side socket continues to be in the listening state, and continues to receive connection requests from other client-side sockets.

2.3. SOCKET connection and TCP connection

When creating a Socket connection, you can specify the transport layer protocol used, and the Socket can support different transport layer protocols (TCP or UDP). When using the TCP protocol for connection, the Socket connection is a TCP connection.

2.4, Socket connection and HTTP connection

Since the Socket connection is usually a TCP connection, once the Socket connection is established, the communication parties can start to send data content to each other until the connection between the two parties is disconnected. However, in actual network applications, the communication between the client and the server often needs to pass through multiple intermediate nodes, such as routers, gateways, firewalls, etc. By default, most firewalls will close connections that have been inactive for a long time, causing the Socket connection to be disconnected. connection, so it needs to tell the network by polling that the connection is active.

The HTTP connection uses the "request-response" method. Not only does the connection need to be established first when making a request, but also the server can reply to the data after the client sends a request to the server.

In many cases, the server needs to actively push data to the client to maintain real-time and synchronization of client and server data. At this time, if both parties establish a Socket connection, the server can directly transmit the data to the client;

If the two parties establish an HTTP connection, the server needs to wait until the client sends a request before sending the data back to the client. Therefore, the client sends connection requests to the server regularly, which can not only keep online, but also "ask" Whether the server has new data, and if so, send the data to the client.

3. The use of Socket in the iOS development process

The following is a brief introduction to the four parts of connecting to the server, sending data to the server, receiving server data, and monitoring input and output streams in iOS development:

3.1. Connect to the server

- (void)connectToHost 
{
    //1.建立连接
    NSString *host =@"127.0.0.1";
    intport =12345;

    //定义C语言输入输出流
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;

    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);

    //把C语言的输入输出流转化成OC对象
    _inputStream = (__bridge NSInputStream *)(readStream);
    _outputStream = (__bridge NSOutputStream *)(writeStream);
    
    //设置代理
    _inputStream.delegate=self;
    _outputStream.delegate=self;

    //把输入输入流添加到主运行循环
    //不添加主运行循环 代理有可能不工作

    [_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

    //打开输入输出流
    [_inputStream open];
    [_outputStream open];
}

3.2. Send data to the server

- (void)sendData
{
    // 把Str转成NSData
    NSData *data =[loginStr dataUsingEncoding:NSUTF8StringEncoding];
    [_outputStream write:data.bytes maxLength:data.length];
}

3.3. Read server data

- (void)readServerData
{
    //建立一个缓冲区 可以放1024个字节
    uint8_t buf[1024];

    //返回实际装的字节数
    NSInteger len = [_inputStream read:buf maxLength:sizeof(buf)];

    //把字节数组转化成字符串
    NSData *data =[NSData dataWithBytes:buf length:len];

    //从服务器接收到的数据
    NSString *recStr =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"%@",recStr);
}

3.4. Comply with the proxy and monitor the input and output streams

-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
	NSLog(@"%@",[NSThread currentThread]);

	//NSStreamEventOpenCompleted = 1UL << 0,//输入输出流打开完成
	//NSStreamEventHasBytesAvailable = 1UL << 1,//有字节可读
	//NSStreamEventHasSpaceAvailable = 1UL << 2,//可以发放字节
	//NSStreamEventErrorOccurred = 1UL << 3,//连接出现错误
	//NSStreamEventEndEncountered = 1UL << 4//连接结束

	switch(eventCode) {
	    caseNSStreamEventOpenCompleted:
	    
	    NSLog(@"输入输出流打开完成");
	    break;

	    caseNSStreamEventHasBytesAvailable:
	    NSLog(@"有字节可读");

	    [self readServerData];
	    break;

	    caseNSStreamEventHasSpaceAvailable:

	    NSLog(@"可以发送字节");

	    break;

	    caseNSStreamEventErrorOccurred:
    
	    NSLog(@"连接出现错误");

	    break;

	    caseNSStreamEventEndEncountered:
    
	    NSLog(@"连接结束");

	    //关闭输入输出流

	    [_inputStream close];
	    [_outputStream close];

	    //从主运行循环移除

	    [_inputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
	    [_outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
	    break;

	    default:
	    break;

	}

}

Guess you like

Origin blog.csdn.net/ID314846818/article/details/52598409
Recommended