1. Various network protocols: TCP/IP, SOCKET, HTTP, etc.
The seventh layer of the network is from bottom to top, namely the physical layer, the data link layer, the network layer, the transport layer, the session layer, the presentation layer and the application layer.
Among them, the physical layer, data link layer and network layer are usually called media layer, and are the objects studied by network engineers;
The transport layer, session layer, presentation layer and application layer are called host layer, which are content that users are targeted and concerned about.
http protocol corresponds to the application layer
TCP protocol corresponds to the transport layer
The IP protocol corresponds to the network layer
The three are essentially incomparable. What's more, the HTTP protocol is based on TCP connection.
TCP/IP is the transport layer protocol, which mainly solves how data is transmitted on the network; while HTTP is the application layer protocol, which mainly solves how data is wrapped.
When transmitting data, we can only use the transport layer (TCP/IP), but in that case, since there is no application layer, the data content cannot be recognized. If we want to make the transmitted data meaningful, we must use the application layer protocol. There are many application layer protocols, including HTTP, FTP, TELNET, etc., and we can also define the application layer protocol yourself. WEB uses HTTP as the transport layer protocol to encapsulate HTTP text information, and then uses TCP/IP as the transport layer protocol to send it to the network. Socket is an encapsulation of the TCP/IP protocol. Socket itself is not a protocol, but a calling interface (API). Only through Socket can we use the TCP/IP protocol.
2. The difference between Http and Socket connections
I believe that many beginners who are new to mobile phone network development want to know what the difference between Http and Socket connections are. I hope that through their own simple understanding, it can be helpful to beginners.
2.1. TCP connection
To understand Socket connection, you must first understand TCP connection. The networking function of mobile phones is because the underlying mobile phone implements the TCP/IP protocol, which allows mobile phone terminals to establish TCP connections through wireless networks. The TCP protocol can provide an interface to the upper-layer network, so that the transmission of upper-layer network data is established on a "undifferentiated" network.
To establish a TCP connection, you need to go through a "three-way handshake":
The first handshake: the client sends a syn packet (syn=j) to the server and enters the SYN_SEND state, waiting for the server to confirm;
The second handshake: When the server receives the syn packet, it must confirm the client's SYN (ack=j+1), and also send a SYN packet (syn=k), that is, the SYN+ACK packet. At this time, the server enters the SYN_RECV state;
The third handshake: The client receives the server's SYN+ACK packet and sends the confirmation packet ACK (ack=k+1) to the server. After the packet is sent, the client and the server enter the ESTABLISHED state and complete the three handshakes.
gripThe packet transmitted during the hand process does not contain data. After three handshakes, the client and the server officially start transmitting data. Ideally, once a TCP connection is established, the TCP connection will be maintained until either party of the communication actively closes the connection. When disconnecting, both the server and the client can actively initiate a request to disconnect the TCP connection. The disconnection process requires "four handshakes" (the process will not be written in detail, that is, the server and the client interact and finally determine the disconnection)
2.2. HTTP connection
The HTTP protocol is the HypertextTransfer Protocol, which 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 the TCP protocol.
The most prominent feature of HTTP connections is that each request sent by the client requires a server to send a reply, and after the request is completed, the connection will be released automatically. The process from establishing a connection to closing a connection is called a "one-time connection."
1) In HTTP 1.0, each request from the client requires a separate connection to be established, and the connection will be automatically released after processing this request.
2) In HTTP 1.1, multiple requests can be processed in a single connection, and multiple requests can be made overlaid, without waiting for one request to end before sending the next request.
Since HTTP will actively release the connection after each request is completed, HTTP connection is a "short connection". To keep the client program online, you need to constantly initiate connection requests to the server. The usual practice is to instantly not obtain any data, and the client also keeps sending a "stay connected" request to the server every fixed period of time. The server responds to the client after receiving the request, indicating that it knows that the client is "online". If the server cannot receive the client's request for a long time, it is considered that the client is "offline". If the client cannot receive the server's reply for a long time, it is considered that the network has been disconnected.
3. SOCKET principle
3.1. Socket (socket) concept
Sockets are the cornerstone of communication and are the basic operating unit of network communication that supports TCP/IP protocol. It is an abstract representation of the endpoint during network communication, which contains five necessary information 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 port of the remote process.
When the application layer communicates 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 go through the same
TCP protocol port transmits data. In order to distinguish different application processes and connections, many computer operating systems provide socket interfaces for applications to interact with the TCP/IP protocol. The application layer can distinguish communication from different application processes or network connections through the Socket interface between the application layer and the transport layer to realize concurrent services for data transmission.
3.2. Establish a socket connection
To establish a Socket connection, at least one pair of sockets is required, one running on the client, called ClientSocket, and the other running on the server, called ServerSocket.
The connection process between sockets is divided into three steps: server listening, client request, and connection confirmation.
Server listening: Server-side sockets do not locate specific client sockets, but are in a state of waiting for connection, monitoring the network status in real time, and waiting for client connection requests.
Client request: refers to the client's socket making a connection request, and the target to be connected is the server-side socket. To do this, the client's socket must first describe the socket of the server to which it is 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 monitors or receives the connection request of the client socket, it responds to the client socket request, establishes a new thread, and sends the description of the server-side socket to the client. Once the client confirms this description, both parties will officially establish a connection. The server-side socket continues to be in the listening state and continues to receive connection requests from other client sockets.
3.3. SOCKET connection and TCP connection
When creating a Socket connection, you can specify the transport layer protocol used. Socket can support different transport layer protocols (TCP or UDP). When connecting using the TCP protocol, the Socket connection is a TCP connection.
3.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 sending data content to each other until the connection between the two parties is disconnected. However, in actual network applications, communication between clients and servers often requires crossing multiple intermediate nodes, such as routers, gateways, firewalls, etc. Most firewalls will turn off connections that are inactive for a long time by default, resulting in disconnection of Socket connections. Therefore, it is necessary to tell the network that the connection is active through polling.
HTTP connections use the "request-response" method. Not only does it require a connection to be established when requesting, but the client also needs to make a request to the server before the server can reply to the data. In many cases, the server needs to actively push data to the client to maintain real-time and synchronization between the client and server data. At this time, if both parties establish a Socket connection, the server can directly transfer the data to
Client; If both parties establish an HTTP connection, the server needs to wait until the client sends a request before transmitting the data back to the client. Therefore, the client sends a connection request to the server regularly, which not only can remain online, but also "query" the server whether there is new data. If there is, pass the data to the client.
Here we use Socket to implement the function of a chat room, and I won't introduce it here about the server.
1: The first input stream and the output stream and a message array in the header file
@interfaceViewController (){ NSInputStream *_inputStream;// Corresponding input stream NSOutputStream *_outputStream;// Corresponding output stream } @property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewConstraint; @property (weak, nonatomic) IBOutlet UITableView *tableView; @property (nonatomic, strong) NSMutableArray *chatMsgs;//Chat message array @end Lazy loading this message array -(NSMutableArray *)chatMsgs{ if(!_chatMsgs) { _chatMsgs =[NSMutableArray array]; } return_chatMsgs; }
Two: Implement monitoring of input and output streams
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{ NSLog(@"%@",[NSThread currentThread]); //NSStreamEventOpenCompleted = 1UL << 0,//Input and output stream is opened complete//NSStreamEventHasBytesAvailable = 1UL << 1,//There are bytes to be read//NSStreamEventHasSpaceAvailable = 1UL << 2,//Bytes can be issued//NSStreamEventErrorOccurred = 1UL << 3,//There is an error in the connection//NSStreamEventEndEncountered = 1UL << 4//The connection ends switch(eventCode) { caseNSStreamEventOpenCompleted: NSLog(@"Input and Output Stream Open Completed"); break; caseNSStreamEventHasBytesAvailable: NSLog(@"Bytes to read"); [self readData]; break; caseNSStreamEventHasSpaceAvailable: NSLog(@"Can send bytes"); break; caseNSStreamEventErrorOccurred: NSLog(@"The connection error occurred"); break; caseNSStreamEventEndEncountered: NSLog(@"Connection ends"); //Close the input and output stream [_inputStream close]; [_outputStream close]; //Remove from the main run loop [_inputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; [_outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; break; default: break; } }
Three: Link to the server
1- (IBAction)connectToHost:(id)sender { //1. Establish a connection NSString *host =@"127.0.0.1"; intport =12345; //Define the input and output stream of C language CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream); //Convert the input and output streams of C language into OC objects _inputStream = (__bridge NSInputStream *)(readStream); _outputStream = (__bridge NSOutputStream *)(writeStream); //Set the proxy _inputStream.delegate=self; _outputStream.delegate=self; //Add the input input stream to the main running loop //No main running loop is added. The agent may not work. [_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; [_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; //Open the input and output stream [_inputStream open]; [_outputStream open]; }
Four: Log in
- (IBAction)loginBtnClick:(id)sender { //Log in //Send username and password //When doing it here, just send the username and password without sending it //If you want to log in, the sent data format is "iam:zhangsan"; //If you want to send a chat message, the data format is "msg:did you have dinner"; //Login command 11NSString *loginStr =@"iam:zhangsan"; //Convert Str to NSData NSData *data =[loginStr dataUsingEncoding:NSUTF8StringEncoding]; [_outputStream write: maxLength:]; }
Five: Read server data
#pragmamark reads the data returned by the server -(void)readData{ //Create a buffer and can put 1024 bytes uint8_t buf[1024]; //Return the actual number of bytes installed NSInteger len = [_inputStream read:buf maxLength:sizeof(buf)]; //Convert byte array into string NSData *data =[NSData dataWithBytes:buf length:len]; //Data received from the server NSString *recStr =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",recStr); [self reloadDataWithText:recStr]; }
Six: Send data
-(BOOL)textFieldShouldReturn:(UITextField *)textField{ NSString *text =; NSLog(@"%@",text); //Chat information NSString *msgStr = [NSString stringWithFormat:@"msg:%@",text]; //Convert Str to NSData10NSData *data =[msgStr dataUsingEncoding:NSUTF8StringEncoding]; //Refresh the table [self reloadDataWithText:msgStr]; //Send data [_outputStream write: maxLength:]; //After sending the data, clear the textField =nil; returnYES; }
7: Implement data display, and every time the message is sent, it will scroll to the corresponding position
-(void)reloadDataWithText:(NSString *)text{ [ addObject:text]; [ reloadData]; //There are many data, you should scroll up NSIndexPath *lastPath = [NSIndexPath indexPathForRow: -1inSection:0]; [ scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; } #pragmamark table data source -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ ; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { staticNSString *ID =@"Cell"; UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:ID]; =[]; returncell; } -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ [ endEditing:YES]; }
8: Listening to the keyboard changes
//Speak the keyboard [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbFrmWillChange:) name:UIKeyboardWillChangeFrameNotificationobject:nil]; } -(void)kbFrmWillChange:(NSNotification *)noti{ NSLog(@"%@",); //Get the height of the window CGFloat windowH =[UIScreen mainScreen].; //Frm at the end of the keyboard CGRect kbEndFrm =[[UIKeyboardFrameEndUserInfoKey] CGRectValue]; //Get the y value of the end of the keyboard CGFloat kbEndY =; = windowH -kbEndY; }
Text/Hold your left hand and never leave (author of Jianshu)
Original link: /p/6b64d8ac62e3
The copyright belongs to the author. Please contact the author to obtain authorization when reprinting and mark "Brand Book Author".
The above is the information sorting out the IOS development network chapter - Socket programming. We will continue to add relevant information in the future. Thank you for your support for this site!