IOS Development Network Chapter-socket programming detailed _ios

Source: Internet
Author: User
Tags ack constant readable

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

The seven layers of the network are the physical layer, the data link layer, the network layer, the Transport layer, the session layer, the presentation layer and the application layer respectively.

The physical layer, the data link layer and the network layer are usually called the media layer, which is the object of the network engineers.

The transport layer, the session layer, the presentation layer and the application layer are called the host layer, which is the content that the user faces and cares about.

HTTP protocol corresponds to application tier

TCP protocol corresponds to transport layer

IP protocol corresponds to the network layer

There is no comparability of the three by nature. Moreover, the HTTP protocol is based on TCP connections.

TCP/IP is a Transport layer protocol that mainly addresses how data is transmitted over the network, while HTTP is an application layer protocol that mainly addresses how data is packaged.

When we transfer data, we can use only the transport layer (TCP/IP), but in that case, because there is no application layer, it can not recognize the data content, if you want to make the transmission of data meaningful, you must use the Application layer protocol, the application layer protocol, there are HTTP, FTP, Telnet You can also define the application layer protocol yourself. The web uses HTTP as a transport Layer protocol to encapsulate HTTP text information, and then use TCP/IP as a Transport layer protocol to send it to the network. Socket is the TCP/IP protocol encapsulation, the socket itself is not a protocol, but a call interface (API), through the socket, we can use the TCP/IP protocol.

Two, HTTP and socket connection differences

I believe that many novice mobile phone networking development friends want to know what is the difference between HTTP and socket connection, hope that through their own simple understanding can help beginners.

2.1, TCP connection

To understand the socket connection, first understand the TCP connection. The mobile phone can use the networking function because the mobile phone at the bottom of the implementation of the TCP/IP protocol, the mobile phone terminal through the wireless network to establish a TCP connection. The TCP protocol can provide an interface to the upper layer network, so that the transmission of the upper layer network data is based on the "No Difference" network.

Establishing a TCP connection requires a "three handshake":

First handshake: The client sends the SYN packet (SYN=J) to the server, and enters the Syn_send state, waiting for the server to confirm;

Second handshake: The server received the SYN packet, must confirm the customer's SYN (ACK=J+1), but also send a SYN packet (syn=k), that is Syn+ack packet, at this time the server into the SYN_RECV state;

Third handshake: The client receives the server Syn+ack packet, sends the confirmation packet ack (ACK=K+1) to the server, this packet sends completes, the client and the server enters established state, completes three times handshake.

holding the hand in the process of the transfer of the packet does not contain data, three times after the handshake, the client and server before the official start to transfer data. Ideally, once a TCP connection is established, the TCP connection is maintained until either side of the communication actively closes the connection. When disconnected, both the server and the client can initiate a request to disconnect the TCP connection, and the disconnect process requires a "four handshake" (the process is not fine, that is, the server and client interaction, the final determination of the disconnect)

2.2, HTTP connection

HTTP protocol, the Hypertext Transfer Protocol (Hypertexttransfer Protocol), is the foundation of Web networking and one of the common protocols of mobile networking, and HTTP protocol is an application based on TCP protocol.

The most notable feature of HTTP connections is that each request sent by the client requires a server loopback response, and the connection is actively released after the request is completed. The process from establishing a connection to closing a connection is called a "once connection."

1 in HTTP 1.0, each request from the client requires a separate connection to be established, and the connection is automatically released after the request has been processed.

2 in HTTP 1.1, you can handle multiple requests in a single connection, and multiple requests can overlap, without waiting for a request to end before sending the next request.

Because HTTP actively frees connections after each request, HTTP connections are a "short connection" that requires constant connection requests to the server to keep the client program online. The usual practice is to not need to get any data immediately, the client also maintains every fixed time to send the server a "Stay Connected" request, the server after receiving the request to the client reply, indicating that the client "online." If the server is unable to receive the client's request for a long time, the client is considered "offline" and if the client cannot receive a reply from the server for a long time, the network has been disconnected.

Three, Socket principle

3.1, socket (socket) concept

Socket (socket) is the cornerstone of communication, is the basic operating unit of network communication that supports TCP/IP protocol. It is the abstract representation of the endpoint in network communication, including the five kinds of information that must be used for network communication: The Protocol of the 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 is communicating through the transport layer, TCP encounters problems that simultaneously provide concurrent services for multiple application processes. Multiple TCP connections or multiple application processes may need to pass the same

The TCP protocol port transmits data. To differentiate between 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 communicate with the transport layer through the socket interface to distinguish the communication from different application processes or network connections, and realize the concurrent service of data transmission.

3.2. Establish socket connection

Establishing a socket connection requires at least a pair of sockets, one running on the client, called Clientsocket, and the other running on the server side, called ServerSocket.

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

Server listening: server-side sockets do not locate specific client sockets, but are in the state of waiting for connections, real-time monitoring of network status, waiting for client connection requests.

Client request: Refers to the client socket to make a connection request, the target to be connected is the server-side socket. To do this, the socket for the client must first describe the socket of the server 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 supervisor hears or says that a connection request for a client socket is received, in response to the client socket request, create a new thread, the server-side socket description to the client, once the client confirmed this description, the two sides formally establish a connection. While the server-side socket continues to be listening, it 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, which can support different transport layer protocols (TCP or UDP), which is a TCP connection when the TCP protocol is used to connect.

3.4, Socket connection and HTTP connection

Since the socket connection is typically a TCP connection, once the socket connection is established, the two sides of the communication can start sending the data to each other until the connection is disconnected. But in the actual network application, communication between clients to the server often needs to traverse multiple intermediate nodes, such as routers, gateways, firewalls, and so on, most firewalls will shut down a long inactive connection and cause the socket connection to disconnect, so it needs to be polled to tell the network that the connection is active.

The HTTP connection uses a "request-response" approach, not only to establish a connection when the request is made, but also to require the client to make a request to the server before the server can reply to the data. In many cases, a server-side initiative is required to push data to the client, keeping the client and server data in real-time and synchronized. At this point, if the two sides establish a socket connection, the server can directly transfer data to

Client; If the two sides establish an HTTP connection, the server needs to wait until the client sends a request to send the data back to the client, so the client sends the connection request to the server at regular intervals, not only to stay online, but also to "ask" if the server has new data and to pass the data to the client.

Here we use the socket to implement a chat room function, about the server here is not introduced

One: the first input stream and the output stream and an array of messages 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 load This message array

-(Nsmutablearray *) chatmsgs{

if (!_chatmsgs) {

_chatmsgs =[nsmutablearray array];

}

return_chatmsgs;

}

Second: The realization of input and output flow monitoring

-(void) stream: (Nsstream *) Astream handleevent: (nsstreamevent) eventcode{NSLog (@ "%@", [Nsthread CurrentThread]); nsstreameventopencompleted = 1UL << 0,//Input Output stream open complete//nsstreameventhasbytesavailable = 1UL << 1,//bytes readable// nsstreameventhasspaceavailable = 1UL << 2,//can issue byte//nsstreameventerroroccurred = 1UL << 3,//connection Error// nsstreameventendencountered = 1UL << 4//connection End switch (eventcode) {Casensstreameventopencompleted:nslog (@ "Input output stream open

Completed ");

Break

Casensstreameventhasbytesavailable:nslog (@ "bytes readable");

[Self readdata];

Break

Casensstreameventhasspaceavailable:nslog (@ "can send bytes");

Break

Casensstreameventerroroccurred:nslog (@ "connection error");

Break

Casensstreameventendencountered:nslog (@ "End of Connection");

Turn off the input output stream [_inputstream close];

[_outputstream Close];

Remove [_inputstream removefromrunloop:[nsrunloop Mainrunloop] Formode:nsdefaultrunloopmode from the main run loop];

[_outputstream Removefromrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];

Break Default:bReak;

 }

}

Third: Linked server

1-(Ibaction) Connecttohost: (ID) Sender {

//1. Establish 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);

Converting the input and output stream of C language into OC object

_inputstream = (__bridge Nsinputstream *) (readstream);

_outputstream = (__bridge Nsoutputstream *) (writestream);

Set up Agent

_inputstream.delegate=self;

_outputstream.delegate=self;

Add input stream to main run loop

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

[_inputstream scheduleinrunloop:[nsrunloop Mainrunloop] Formode: Nsdefaultrunloopmode];

[_outputstream Scheduleinrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];

Open the input output stream

[_inputstream open];

[_outputstream open];

}

Four: Landing

-(Ibaction) Loginbtnclick: (ID) Sender {/

/login

//Send username and password

//When doing here, only send username, password do not send

///If you want to log in, send the data format as " Iam:zhangsan ";

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

Log in instruction 11NSString *loginstr =@ "Iam:zhangsan";

Turn str into nsdata

nsdata *data =[loginstr datausingencoding:nsutf8stringencoding];

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

}

Five: Read server data

#pragmamark read the data returned by the server

-(void) readdata{

//Set up a buffer can be placed 1024 bytes

uint8_t buf[1024];

Returns the number of bytes actually loaded

nsinteger len = [_inputstream read:buf maxlength:sizeof (BUF)];

Converts a byte array 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];

}

Six: Send data

-(BOOL) Textfieldshouldreturn: (Uitextfield *) textfield{

nsstring *text =textfield.text;

NSLog (@ "%@", text);

Chat information

nsstring *msgstr = [NSString stringwithformat:@ "msg:%@", text];

Turn str into nsdata10nsdata *data =[msgstr datausingencoding:nsutf8stringencoding];

Refresh Table

[self reloaddatawithtext:msgstr];

Send Data

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

Send out data, empty TextField

textfield.text =nil;

Returnyes;

}

Seven: the implementation of data display, and every message will be sent to scroll to the corresponding location

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

[Self.chatmsgs addobject:text];

[Self.tableview Reloaddata];

More data should be rolled up

nsindexpath *lastpath = [Nsindexpath indexpathforrow:self.chatmsgs.count-1insection:0];

[Self.tableview Scrolltorowatindexpath:lastpath Atscrollposition:uitableviewscrollpositionbottom Animated:YES];

}

data source for #pragmamark 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];

}

Eight: Monitoring the keyboard changes

Listening on 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 end of frm

cgrect kbendfrm =[noti.userinfo[uikeyboardframeenduserinfokey] cgrectvalue];

Gets the Y-value of the keyboard end

cgfloat kbendy =kbendfrm.origin.y;

Self.inputViewConstraint.constant = Windowh-kbendy;

}

Text/Left hand (Jane book author)
Original link: http://www.jianshu.com/p/6b64d8ac62e3
Copyright belongs to the author, reproduced please contact the author to obtain authorization, and labeled "Jane book author."

The above is the iOS Development Network-socket programming data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!

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.