IOS Web Development Socket Programming Details

  • 2020-10-31 22:00:35
  • OfStack

1. Network protocols: TCP/IP, SOCKET, HTTP, etc

The 7 network layers are physical layer, data link layer, network layer, transport layer, session layer, presentation layer and application layer from bottom to top.

The physical layer, data link layer and network layer are commonly referred to as media layer, which are studied by network engineers.

The transport layer, the session layer, the presentation layer and the application layer are called the host layer and are the content that users are oriented and concerned about.

The http protocol corresponds to the application layer

The tcp protocol corresponds to the transport layer

The ip protocol corresponds to the network layer

There is essentially no comparison between the three. Moreover, the HTTP protocol is based on THE TCP connection.

TCP/IP is the transport layer protocol, which mainly solves the problem of how to transfer data in the network. HTTP, on the other hand, is an application layer protocol that mainly deals with how to package data.

When I in data transmission, can only use the transport layer (TCP/IP), but in that case, since there is no application layer, can't identify the data content, if you want to make meaningful transmission of data, you must use the application layer protocol, the application layer protocol is very much, have HTTP, FTP, TELNET, etc., can also define your own application layer protocol. WEB USES HTTP as the transport layer protocol to encapsulate HTTP text, and then USES TCP/IP as the transport layer protocol to send it over the network. Socket is the encapsulation of TCP/IP protocol. Socket is not a protocol itself, but a call interface (API). Through Socket, we can use TCP/IP protocol.

2. Differences between Http and Socket connections

Believe that many novice mobile phone network development friends want to know what the difference between Http and Socket connection, hope that through their own simple understanding can be helpful to beginners.

2.1 TCP connection

To understand the Socket connection, understand the TCP connection. The reason why mobile phones can use networking function is that the underlying layer of mobile phones implements TCP/IP protocol, which enables mobile terminals to establish TCP connection through wireless network. The TCP protocol provides an interface to the upper network so that the transmission of the upper network data is based on an "undifferentiated" network.

Setting up an TCP connection requires "three handshakes" :

The first handshake: the client sends the syn package (syn=j) to the server, enters the state of SYN_SEND, and waits for the server's confirmation.

The second handshake: when the server receives the syn packet, it must confirm the client's SYN (ack=j+1), and at the same time, it also sends one SYN packet (syn=k), that is, SYN+ACK packet. At this time, the server enters the STATE of SYN_RECV.

The third handshake: the client receives SYN+ACK packet from the server and sends confirmation packet ACK(ack=k+1) to the server. After this packet is sent, the client and the server enter ESTABLISHED state and shake hands for three times.

The packets transmitted during the handshake do not contain data. After the three handshakes, the client and server officially start transmitting data. Ideally, the TCP connection is established once, and the TCP connection is maintained by the 1 until either 1 of the communicating parties actively closes the connection. When the connection is disconnected, both the server and the client can initiate a request to disconnect the TCP connection, and the disconnection process needs to go through "four handshakes".

2.2 HTTP connection

HTTP protocol is the hypertext transfer protocol (HypertextTransfer Protocol), which is the basis of Web networking and one of the protocols commonly used in mobile networking. HTTP protocol is an application based on TCP protocol.

The most significant feature of the HTTP connection is that each request sent by the client requires a server echo response, and at the end of the request, the connection is actively released. The process from establishing a connection to closing a connection is called "connection one."

1) In HTTP 1.0, each client request required a separate connection to be established and the connection was automatically released after the request was processed.

2) In HTTP 1.1, multiple requests can be processed in a single connection, and multiple requests can be overlapped, without the need to wait for the end of one request before sending the next request.

Since HTTP actively releases the connection at the end of each request, HTTP is a "short connection" that requires constant connection requests to the server to keep the client program online. The usual practice is to immediately not need to obtain any data, and the client also maintains a "stay connected" request to the server every 1 fixed period of time, after receiving the request, the server replies to the client, indicating that it knows the client is "online". If the server fails to receive a request from the client for a long time, the client is considered "offline"; if the client fails to receive a reply from the server for a long time, the network is considered disconnected.

3. The principle of SOCKET

3.1 Concept of socket (socket

Socket (socket) is the cornerstone of communication and the basic operating unit of network communication that supports TCP/IP protocol. It is an abstract representation of endpoints in the process of network communication and contains five kinds 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 port of the remote process.

When the application layer communicates through the transport layer, TCP encounters the problem of providing concurrent services to multiple application processes at the same time. Multiple TCP connections or multiple application processes may need to pass through the same one

TCP protocol port for data transfer. To distinguish between different application processes and connections, many computer operating systems provide sockets (Socket) interfaces for applications to interact with the TCP/IP protocol. The application layer and the transport layer can distinguish communication from different application processes or network connections through the Socket interface to realize concurrent services of data transmission.

3.2 Establish socket connection

Setting up an Socket connection requires at least one pair of sockets, one running on the client side, called ClientSocket, and one running on the server, called ServerSocket.

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

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

Client request: Refers to a socket on the client side that makes a connection to the target socket on the server side. To do this, the client socket must first describe the socket to which it is connecting, 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 to or receives the connection request of the client-side socket, a new thread is created in response to the request of the client-side socket, and the description of the server-side socket is sent to the client. Once the client confirms the description, the two parties officially establish the connection. While the server-side socket continues to be listened to, it continues to receive connection requests from other client-side sockets.

3.3 SOCKET connection and TCP connection

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

3.4. Socket connection and HTTP connection

As an Socket connection is usually an TCP connection, once the Socket connection 1 is established, the communicating parties can begin to send data content to each other until the connection is broken. But in actual network applications, the communication between the client to the server often need through multiple intermediate nodes, such as routers, gateways, firewalls, etc., most of the default firewall will be shut down for a long time in the inactive state of the connection and cause Socket connection disconnected, so you need to told network by polling, the connection is active.

The HTTP connection, on the other hand, USES a request-response approach, requiring not only a connection to be established at the time of the request, but also a request from the client to the server before the server can reply to the data. In many cases, the server side is required to actively push data to the client side to keep real-time and synchronous data between the client side and the server. At this point, if the Socket connection is established, the server can send the data directly to

The client; If both sides is HTTP connections, the server needs to wait for the client to send one request to the data back to the client, as a result, the client sends a connection request to the server regularly can not only keep online, but also in the "ask" if there is a new data server, if there will be data to the client.

Here we use Socket to achieve 1 chat room function, about the server here is not introduced

1: The first input stream and output stream and 1 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 of this message array 

-(NSMutableArray *)chatMsgs{

if(!_chatMsgs) {

_chatMsgs =[NSMutableArray array];

}

return_chatMsgs;

}

2: Achieve input and output stream monitoring


-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{

NSLog(@"%@",[NSThread currentThread]);

//NSStreamEventOpenCompleted = 1UL << 0,// I/O stream open completed //NSStreamEventHasBytesAvailable = 1UL << 1,// There are bytes to read //NSStreamEventHasSpaceAvailable = 1UL << 2,// You can issue bytes //NSStreamEventErrorOccurred = 1UL << 3,// Connection error //NSStreamEventEndEncountered = 1UL << 4// Connect the end of the 

switch(eventCode) {

caseNSStreamEventOpenCompleted:

NSLog(@" I/O stream open completed ");

break;

caseNSStreamEventHasBytesAvailable:

NSLog(@" There are bytes to read ");

[self readData];

break;

caseNSStreamEventHasSpaceAvailable:

NSLog(@" You can send bytes ");

break;

caseNSStreamEventErrorOccurred:

NSLog(@" Connection error ");

break;

caseNSStreamEventEndEncountered:

NSLog(@" Connect the end of the ");

// Close the I/O stream 

[_inputStream close];

[_outputStream close];

// Removed from the main run loop 

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

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

break;

default:

break;

}

}

3: Link server


1- (IBAction)connectToHost:(id)sender {

//1. Establish a connection 

NSString *host =@"127.0.0.1";

intport =12345;

// define C Language input/output stream 

CFReadStreamRef readStream;

CFWriteStreamRef writeStream;

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

// the C Language input and output flow into OC object 

_inputStream = (__bridge NSInputStream *)(readStream);

_outputStream = (__bridge NSOutputStream *)(writeStream);

// Set the agent 

_inputStream.delegate=self;

_outputStream.delegate=self;

// Add the input input stream to the main run loop 

// Do not add the main run loop   The agent may not work 

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

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

// Open the I/O stream 

[_inputStream open];

[_outputStream open];

}

4: login


- (IBAction)loginBtnClick:(id)sender {

// The login 

// Send the user name and password 

// When you do it here, you just send the username, you don't have to send the password 

// If you want to log in, the format of the data sent is  "iam:zhangsan";

// If you want to send a chat message, the data format is  "msg:did you have dinner";

// Login instructions 11NSString *loginStr =@"iam:zhangsan";

// the Str into NSData

NSData *data =[loginStr dataUsingEncoding:NSUTF8StringEncoding];

[_outputStream write:data.bytes maxLength:data.length];

}

5: Read server data


#pragmamark  Read the data returned by the server 

-(void)readData{

// To establish 1 A buffer   Can put 1024 bytes 

uint8_t buf[1024];

// Returns the actual number of bytes loaded 

NSInteger len = [_inputStream read:buf maxLength:sizeof(buf)];

// Converts an array of bytes to a 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];

}

6: Send data


-(BOOL)textFieldShouldReturn:(UITextField *)textField{

NSString *text =textField.text;

NSLog(@"%@",text);

// Chat messages 

NSString *msgStr = [NSString stringWithFormat:@"msg:%@",text];

// the Str into NSData10NSData *data =[msgStr dataUsingEncoding:NSUTF8StringEncoding];

// The refresh table 

[self reloadDataWithText:msgStr];

// To send data 

[_outputStream write:data.bytes maxLength:data.length];

// Send the data. Clear it textField

textField.text =nil;

returnYES;

}

7: Realize the display of data, and each time the message is sent, it will scroll to the corresponding position


-(void)reloadDataWithText:(NSString *)text{

[self.chatMsgs addObject:text];

[self.tableView reloadData];

// I have a lot of data, so I should scroll up 

NSIndexPath *lastPath = [NSIndexPath indexPathForRow:self.chatMsgs.count -1inSection:0];

[self.tableView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

}

#pragmamark  Data source of the table 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

returnself.chatMsgs.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

staticNSString *ID =@"Cell";

UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:ID];

cell.textLabel.text =self.chatMsgs[indexPath.row];

returncell;

}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

[self.view endEditing:YES];

}

8: Listen for keyboard changes


// Listening to the keyboard 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbFrmWillChange:) name:UIKeyboardWillChangeFrameNotificationobject:nil];

}

-(void)kbFrmWillChange:(NSNotification *)noti{

NSLog(@"%@",noti.userInfo);

// Gets the height of the window 

CGFloat windowH =[UIScreen mainScreen].bounds.size.height;

// Keyboard-Terminated Frm

CGRect kbEndFrm =[noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

// Get the end of the keyboard y value 

CGFloat kbEndY =kbEndFrm.origin.y;

self.inputViewConstraint.constant = windowH -kbEndY;

}

Text/left hand (Jane author)
The original link: http: / / www jianshu. b64d8ac62e3 com p / 6
The copyright belongs to the author. Please contact the author for authorization and label "The author of the brief book".

Above is IOS development network article - Socket programming data collation, the follow-up continue to supplement relevant information, thank you for your support to this site!


Related articles: