IOS Socket programming

Source: Internet
Author: User

IOS Socket programming

I. Various network protocols: TCP/IP, SOCKET, HTTP, etc.
The layer-7 network consists of the physical layer, data link layer, network layer, transmission layer, Session Layer, presentation layer, and application layer.
The physical layer, data link layer, and network layer are usually called media layers, which are the objects of network engineers;
The transport layer, Session Layer, presentation layer, and application layer are called the host layer, which are user-oriented and concerned content.
The http protocol corresponds to the application layer.
The tcp protocol corresponds to the transport layer
The IP protocol corresponds to the network layer.
They are essentially incomparable. Moreover, HTTP is based on TCP connections.
TCP/IP is the transport layer protocol, which mainly solves how data is transmitted over the network. HTTP is the application layer protocol and mainly solves how to package data.
When we transmit data, we can only use the transport layer (TCP/IP). However, since there is no application layer, we cannot identify the data content. If we want to make the transmitted data meaningful, you must use the application layer protocol. There are many application layer protocols, including HTTP, FTP, and TELNET. You can also define the application layer protocol by yourself. The 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 the encapsulation of TCP/IP protocol. Socket itself is not a protocol, but an interface (API) called. Through Socket, we can use TCP/IP protocol.
Ii. Differences between Http and Socket connections
I believe that many new online mobile phone developers want to know what is the difference between Http and Socket connections, and hope that they can help beginners through their own simple understanding.
2.1 TCP Connection
To understand the Socket connection, you must first understand the TCP connection. The mobile phone can use the internet function because the mobile phone bottom layer implements the TCP/IP protocol, which enables the mobile terminal to establish a TCP connection through the wireless network. The TCP protocol can provide interfaces for upper-layer networks, so that data transmission over the upper-Layer Networks is established on a "non-differentiated" network.
To establish a TCP connection, you must go through the "three-way handshake ":
The first handshake: the client sends the syn Packet (syn = j) to the server and enters the SYN_SEND status, waiting for confirmation from the server;
The second handshake: when the server receives the syn packet, it must confirm the customer's SYN (ack = j + 1) and send a SYN Packet (syn = k), that is, the SYN + ACK packet, the server enters the SYN_RECV status;
The third handshake: the client receives the server's SYN + ACK package and sends the ACK (ack = k + 1) Confirmation package to the server. After the package is sent, the client and server enter the ESTABLISHED status, complete three handshakes.
The package transmitted during the handshake does not contain data. After three handshakes are completed, the client and the server formally start to transmit data. Ideally, once a TCP connection is established, the TCP connection will remain until either of the two parties closes the connection. When a TCP connection is disconnected, both the server and client can initiate a request to disconnect the TCP connection. The disconnection process must go through the "Four handshakes" (the process is not detailed, that is, the server interacts with the client, final confirmation of disconnection)
2.2. HTTP Connection
HTTP Protocol is the Hyper Text Transfer Protocol (HypertextTransfer Protocol). It is the foundation of Web networking and one of the common protocols for mobile phone networking. HTTP is an application built on TCP Protocol.
The most notable characteristic of HTTP connection is that each request sent by the client requires a server to send a response. After the request ends, the connection is released. The process from establishing a connection to closing a connection is called "One connection ".
1) in HTTP 1.0, each client request requires a separate connection. After processing the request, the connection is automatically released.
2) in HTTP 1.1, multiple requests can be processed in a single connection, and multiple requests can be overlapped without waiting for a request to end before sending the next request.
The connection is automatically released after each HTTP request ends. Therefore, an HTTP connection is a "short connection" that requires the client program to be online, you must constantly initiate connection requests to the server. The common practice is to immediately get no data, and the client also keeps sending a "keep connection" request to the server at a fixed time, after receiving the request, the server replies to the client, indicating that the client is "online ". If the server cannot receive a request from the client for a long time, the client is considered to be "offline". If the client cannot receive a response from the server for a long time, the network is considered disconnected.
Iii. SOCKET Principle
3.1 socket Concept
Socket is the cornerstone of communication and the basic operation unit for network communication that supports TCP/IP protocol. It is an abstract representation of the endpoint in the network communication process. It contains five types of information required for network communication: the protocol used for connection, the IP address of the local host, and 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 data through the transport layer, TCP may encounter concurrent services for multiple application processes at the same time. Multiple TCP connections or multiple application processes may need to transmit data through the same TCP port. To differentiate different application processes and connections, many computer operating systems provide Socket interfaces for applications to interact with TCP/IP protocols. The application layer and the transport layer can use Socket interfaces to distinguish between processes or network connections of different applications to implement concurrent data transmission services.
3.2 establish a socket connection
To establish a Socket connection, you must have at least one Socket. One of them runs on the client, which is called ClientSocket, And the other runs on the server, which is called ServerSocket.
The connection process between sockets is divided into three steps: server listening, client requests, and connection confirmation.
Server listening: the server socket does not locate the specific client socket, but is waiting for connection. It monitors the network in real time and waits for client connection requests.
Client request: the client socket initiates a connection request, and the target is the server socket. Therefore, the client socket must first describe the socket of the server to be connected, point out the address and port number of the socket on the server, and then submit a connection request to the socket on the server.
Connection Confirmation: when the server socket monitors or receives a connection request from the client socket, it responds to the request from the client socket and creates a new thread, send the description of the server socket to the client. Once the client confirms the description, both parties establish a connection. The server socket continues to be in the listening status, 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. 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.
3.4 Socket connection and HTTP Connection
Generally, a Socket connection is a TCP connection. Once a Socket connection is established, both parties can send data to each other until the connection is closed. However, in actual network applications, communication between the client and the server often needs to traverse multiple intermediate nodes, such as routers, gateways, and firewalls, by default, most firewalls disable connections that are not active for a long time and cause the Socket connection to be disconnected. Therefore, the network needs to be notified through polling that the connection is active.
The HTTP connection uses the "request-response" method. Not only do you need to establish a connection during the request, but you also need the client to send 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 ensure real-time and synchronous data between the client and the server. If both parties establish a Socket connection, the server can directly transmit data to the client. If both parties establish an HTTP connection, the server must wait until the client sends a request before sending the data back to the client. Therefore, the client periodically sends a connection request to the server, which can not only be kept online, at the same time, it is also "asking" whether the server has new data. If yes, it will send the data to the client.
Here we use Socket to implement the function of a chat room. We will not discuss the server here.
I. The first input stream and output stream in the header file and a message Array

@ Interface ViewController ()
  
   
{NSInputStream * _ inputStream; // corresponding input stream NSOutputStream * _ outputStream; // corresponding output stream} @ property (weak, nonatomic) IBOutlet writable * inputViewConstraint; @ property (weak, nonatomic) IBOutlet UITableView * tableView; @ property (nonatomic, strong) NSMutableArray * chatMsgs; // chat message array @ end
  

Lazy load this message Array

-(NSMutableArray *)chatMsgs{if (!_chatMsgs) {   _chatMsgs = [NSMutableArray array]; } return _chatMsgs;}

Ii. Listening for input and output streams

-(Void) stream :( NSStream *) aStream handleEvent :( NSStreamEvent) eventCode {NSLog (@ "% @", [NSThread currentThread]); // NSStreamEventOpenCompleted = 1UL <0, // input/output stream opened successfully // NSStreamEventHasBytesAvailable = 1UL <1, // bytes readable // NSStreamEventHasSpaceAvailable = 1UL <2, // bytes can be issued // NSStreamEventErrorOccurred = 1UL <3, // connection error // NSStreamEventEndEncountered = 1UL <4 // connection end switch (eventCode) {case NSStreamEventOpenCompleted: NSLog (@ "input/output stream opened"); break; case NSStreamEventHasBytesAvailable: NSLog (@ "Byte readable"); [self readData]; break; case NSStreamEventHasSpaceAvailable: NSLog (@ "bytes can be sent"); break; case NSStreamEventErrorOccurred: NSLog (@ "connection error"); break; case NSStreamEventEndEncountered: NSLog (@ "connection ended "); // close the input/output stream [_ inputStream close]; [_ outputStream close]; // remove [_ inputStream removeFromRunLoop: [nsunloop mainRunLoop] forMode: NSDefaultRunLoopMode] from the main running cycle; [_ outputStream removeFromRunLoop: [nsunloop mainRunLoop] forMode: NSDefaultRunLoopMode]; break; default: break ;}}

Iii. linked server

-(IBAction) connectToHost :( id) sender {// 1. establish a connection NSString * host = @ "127.0.0.1"; int port = 12345; // define the C language input/output stream CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFStreamCreatePairWithSocketToHost (NULL, (_ bridge CFStringRef) host, port, & readStream, & writeStream); // convert the input and output of C language into OC object _ inputStream = (_ bridge NSInputStream *) (readStream ); _ outputStream = (_ bridge NSOutputStream *) (writeStream); // sets proxy _ inputStream. delegate = self; _ outputStream. delegate = self; // Add the input stream to the main running loop // if you do not add the main running loop proxy, it may not work [_ inputStream scheduleInRunLoop: [nsunloop mainRunLoop] forMode: NSDefaultRunLoopMode]; [_ outputStream scheduleInRunLoop: [nsunloop mainRunLoop] forMode: NSDefaultRunLoopMode]; // open the input/output stream [_ inputStream open]; [_ outputStream open];}

Iv. Login

-(IBAction) loginBtnClick :( id) sender {// log on // send the user name and password // only send the user name when you do this, you do not need to send the password. // if you want to log on, the sent data format is "iam: zhangsan"; // if you want to send a chat message, the data format is "msg: did you have dinner "; // command NSString * loginStr = @" iam: zhangsan "; // convert Str to NSData * data = [loginStr dataUsingEncoding: NSUTF8StringEncoding]; [_ outputStream write: data. bytes maxLength: data. length];}

V. Server Data Reading

# Pragma mark reads the data returned by the server-(void) readData {// you can create a buffer with 1024 bytes of uint8_t buf [1024]. // return the actual number of loaded bytes NSInteger len = [_ inputStream read: buf maxLength: sizeof (buf)]; // convert the byte array to the string NSData * data = [NSData dataWithBytes: buf length: len]; // 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 information NSString * msgStr = [NSString stringWithFormat: @ "msg: % @", text]; // convert Str to NSData * data = [msgStr dataUsingEncoding: NSUTF8StringEncoding]; // refresh the table [self reloadDataWithText: msgStr]; // send data [_ outputStream write: data. bytes maxLength: data. length]; // after the data is sent, the textField is cleared. text = nil; return YES ;}

7. display data and scroll to the corresponding position for each sent message

-(Void) reloadDataWithText :( NSString *) text {[self. chatMsgs addObject: text]; [self. tableView reloadData]; // you can scroll up NSIndexPath * lastPath = [NSIndexPath indexPathForRow: self. chatMsgs. count-1 inSection: 0]; [self. tableView scrollToRowAtIndexPath: lastPath atScrollPosition: Required animated: YES];} # data source of The pragma mark table-(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section {return self. chatMsgs. count;}-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {static NSString * ID = @ "Cell"; UITableViewCell * cell = [tableView preview: ID]; cell. textLabel. text = self. chatMsgs [indexPath. row]; return cell;}-(void) scrollViewWillBeginDragging :( UIScrollView *) scrollView {[self. view endEditing: YES];}

8. Listen for keyboard changes

// Listen to the [[NSNotificationCenter defacenter center] addObserver: self selector: @ selector (kbFrmWillChange :) name: UIKeyboardWillChangeFrameNotification object: nil];}-(void) kbFrmWillChange :( NSNotification *) noti {NSLog (@ "% @", noti. userInfo); // obtain the height of the window CGFloat wh = [UIScreen mainScreen]. bounds. size. height; // Frm CGRect kbEndFrm = [noti. userInfo [UIKeyboardFrameEndUserInfoKey] CGRectValue]; // obtain the end y value of the keyboard CGFloat kbEndY = kbEndFrm. origin. y; self. inputViewConstraint. constant = 20.wh-kbEndY ;}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.