IOS Socket Programming

Source: Internet
Author: User
Tags ack

I. Network protocols: TCP/IP, sockets, HTTP, etc.
The network seven layer is from the bottom up to the physical layer, the data link layer, the network layer, the transport layer, the conversation layer, the presentation layer and the application layer respectively.
The physical layer, the data link layer and the network layer are often called media layers, which are the objects researched by the Network Project division.
The transport layer, the session layer, the presentation layer, and the application layer are referred to as the host layer and are the content that the user is looking for and cares about.
The HTTP protocol corresponds to the application tier
The TCP protocol corresponds to the transport layer
IP protocol corresponding to network layer
The three are not comparable in nature. Moreover, the HTTP protocol is based on TCP connections.


TCP/IP is a Transport layer protocol that mainly addresses how data travels across the network, while HTTP is the application-layer protocol. The main solution is how to package data.
We can only use the Transport layer (TCP/IP) when transferring data, but in that case there is no application layer. Can not identify the data content, false assumptions to make the transmitted data meaningful. You must use the Application layer protocol, and the application layer protocol is very numerous. HTTP, FTP, Telnet, and so on, can also customize the application layer protocol.

The web uses HTTP as the Transport Layer protocol to encapsulate HTTP text information and then send it to the network using TCP/IP as the Transport layer protocol. Socket is the encapsulation of TCP/IP protocol, the socket itself is not a protocol, but a calling interface (API). Through the socket, we have the ability to use the TCP/IP protocol.
Second, HTTP and socket connection differences
I believe many of the novice mobile phone networking development friends want to know what is the difference between the HTTP and socket connection, hope that through their own shallow understanding of the people who have just started learning to be helpful.
2.1. TCP connection
To clear the socket connection. The TCP connection must be clarified first. The ability of the mobile phone to use the networking function is due to the TCP/IP protocol. Enables the mobile terminal to establish a TCP connection over a wireless network. TCP protocol can provide an interface to the upper network, so that the transmission of the upper network data is based on the "No Difference" network.
Setting up a TCP connection requires a "three-time handshake":
First handshake: The client sends a SYN packet (SYN=J) to the server. and enter the Syn_send state, waiting for the server to confirm;
Second handshake: The server receives the SYN packet, must confirm the customer's SYN (ACK=J+1), and at the same time sends a SYN packet (syn=k), that is, the Syn+ack package. At this point the server enters the SYN_RECV state;
Third handshake: The client receives the server's Syn+ack package and sends an acknowledgment packet ack (ACK=K+1) to the server. After this packet is sent, the client and server enter the established state and complete the handshake three times.
Data is not included in the packets that are delivered during the handshake. After three handshakes, the client and server are officially started transmitting data. Ideally, once a TCP connection is established, either party in the communication is actively shutting down the connection before it is active. The TCP connection will be maintained forever. When disconnected, both the server and client are able to proactively initiate a request to disconnect a TCP connection, which requires a "four handshake" (the process is not fine-grained, that is, the server interacts with the client and finally determines the disconnection)
2.2. HTTP connection
The HTTP protocol, the Hypertext Transfer Protocol (Hypertexttransfer Protocol), is the foundation of Web networking and is one of the protocols that are used frequently in mobile phone networking, an application built on top of the TCP protocol.
The most notable feature of an HTTP connection is that each request sent by the client requires a server loopback response, and the connection is actively released after the request has ended.

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. After the request is processed, the connection is released on its own initiative.


2) in HTTP 1.1, you can process multiple requests in a single connection, and multiple requests overlap, without waiting for a request to end before sending the next request.
Because HTTP is actively releasing the connection after each request ends. So an HTTP connection is a "short connection." To maintain the online status of the client program, you need to continually initiate a connection request to the server. As a general practice, no matter what data is needed, the client also keeps sending a "keep-connected" request to the server at regular intervals, and the server responds to the client after it receives the request, indicating that it is "online". If the server is unable to receive client requests for a long time. That the client "offline". If the client cannot receive a reply from the server for a long time, it feels the network has been disconnected.
Three, Socket principle
3.1. Socket (socket) concept
Socket (socket) is the cornerstone of communication and is the basic operating unit of network communication supporting TCP/IP protocol. It is an abstract representation of the endpoint in the network communication process, including the five kinds of information necessary for network communication: The protocol used by the connection. The IP address of the local host. The protocol port of the local process, the IP address of the remote host, the protocol port of the remote process.
When the application layer communicates data through the transport layer, TCP encounters an issue that provides concurrent services for multiple application processes at the same time.

Multiple TCP connections or multiple application processes may require port data transfer through the same TCP protocol. For different application processes and connections, many computer operating systems provide socket (socket) interfaces for applications interacting with the TCP/IP protocol.

The application layer can communicate with the transport layer through the socket interface, differentiate 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 of which executes on the client, called Clientsocket. There is also an execution on the server side, called ServerSocket.
The connection process between sockets is divided into three steps: Server snooping. Client request, Connection acknowledgement.
Server listener: The server side socket does not locate the detailed client socket, but is in a state of waiting for the connection. Monitor network status in real time. Waits for a connection request from the client.


Client request: Refers to the client's socket to make a connection request. The destination to connect to is the server-side socket. To do this, the client's socket must first describe the socket that describes 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 acknowledgement: When a server-side socket hears or receives a connection request to a client socket, a new thread is created in response to a client socket request. The description of the server end socket is sent to the client. Once the client confirms the narrative, the two parties formally establish a connection. The server-side socket continues to be in the listening state. Continue to receive connection requests from other client sockets.
3.3. Socket connection and TCP connection
When you create a socket connection, you can specify the transport layer protocol that is used, and the socket can support different transport layer protocols (TCP or UDP). When a connection is made 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 two parties can start to send the data content to each other until the two-party connection is disconnected.

However, in actual network application, the communication between client and server often needs to traverse multiple intermediary nodes, such as routers, gateways, firewalls, etc., most firewalls will turn off long inactive connections and cause Socket connection disconnection, so it is necessary to tell the network by polling. The connection is in an active state.
The HTTP connection uses a "request-response" approach, which is not only required to establish a connection at the time of the request. The server's ability to reply to the data is required after the client has made a request to the server.


Very many cases. The server side is required to proactively push data to the client. Keep client and server data in real time and in sync. At this point, if the two parties established a socket connection, the server can directly transfer the data to the client; If the two parties establish an HTTP connection, then the server will have to wait until the client sends a request to send the data back to the client, so The client periodically sends a connection request to the server, not only to remain online, but also to "ask" the server for new data at the same time, passing 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 output stream and a message array in the header file

 @interface viewcontroller () <nsstreamdelegate,uitextfielddelegate, Uitableviewdatasource,uitableviewdelegate>{Nsinputstream *_inputstream;//corresponding input streamNsoutputstream *_outputstream;//corresponding output stream}@property(Weak,nonatomic)IboutletNslayoutconstraint *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 = [NSMutableArrayreturn _chatMsgs;}

Second: to realize the input and output stream monitoring

-(voidStream: (Nsstream *) Astream handleevent: (nsstreamevent) eventcode{NSLog(@"%@",[NsthreadCurrentThread]);//nsstreameventopencompleted = 1UL << 0,//input/output stream open//nsstreameventhasbytesavailable = 1UL << 1,//byte readable//nsstreameventhasspaceavailable = 1UL << 2,//capable of issuing bytes//nsstreameventerroroccurred = 1UL << 3,//connection error occurred//nsstreameventendencountered = 1UL << 4//end of connection    Switch(EventCode) { CaseNsstreameventopencompleted:NSLog(@"Input output stream is open"); Break; CaseNsstreameventhasbytesavailable:NSLog(@"byte-readable"); [ SelfReadData]; Break; CaseNsstreameventhasspaceavailable:NSLog(@"ability to send bytes"); Break; CaseNsstreameventerroroccurred:NSLog(@"Connection error occurred"); Break; CaseNsstreameventendencountered:NSLog(@"End of Connection");//Close the input/output stream[_inputstream Close]; [_outputstream Close];//Remove from main execution loop[_inputstream Removefromrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode]; [_outputstream Removefromrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode]; Break;default: Break; }}

Three: Link server

- (ibaction) Connecttohost: (ID) Sender {//1. Establishing a connection  NSString*host = @"127.0.0.1";intPort =12345;//define C language input/output streamCfreadstreamref Readstream;   Cfwritestreamref Writestream; Cfstreamcreatepairwithsockettohost (NULL, (__bridge cfstringref) host, Port, &readstream, &writestream);//convert c input and output stream to OC object_inputstream = (__bridge Nsinputstream *) (Readstream); _outputstream = (__bridge Nsoutputstream *) (Writestream);//Set up proxy_inputstream. Delegate= Self; _outputstream. Delegate= Self;//Add input input stream to main execution loop     //Do not join the main execution loop agent may not work[_inputstream Scheduleinrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode]; [_outputstream Scheduleinrunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];//Open input/output stream[_inputstream Open]; [_outputstream Open]; }

Four: Login

-(ibaction) Loginbtnclick: (ID) Sender {//Login    //Send username and password    //When doing this, just send username,password without sending    //If you want to log in, send the data format as "Iam:zhangsan";    //Suppose you want to send a chat message. The data format is "Msg:did you have dinner";    //Sign-in instructionsNSString*Loginstr=@"Iam:zhangsan";//Turn str into NSDataNSData*Data = [Loginstr datausingencoding:nsutf8stringencoding]; [_outputstream write:Data.bytesMaxLength:Data.Length]; }

Five: Read server data

 #pragma mark Read the data returned by the server -(void ) readdata{//Create a buffer    Capable of putting 1024 bytes  uint8_t buf[1024 ];     //Returns the number of bytes actually loaded  nsinteger  len = [_inputstream read:buf maxlength: (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 = [NSStringstringwithformat:@"msg:%@", text];//Turn str into NSDataNSData *data = [MsgStr datausingencoding:nsutf8stringencoding];//Refresh table[ SelfRELOADDATAWITHTEXT:MSGSTR];//Send data[_outputstream Write:data. BytesMaxlength:data. Length];//Send out data, empty TextFieldTextField. Text=Nil;return YES;}

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

-(void) Reloaddatawithtext: (NSString*) text{[ Self. ChatmsgsAddobject:text]; [ Self. TableViewReloaddata];//Data many, should scroll upwards    Nsindexpath*lastpath = [NsindexpathIndexpathforrow: Self. Chatmsgs. Count-1Insection:0]; [ Self. TableViewScrolltorowatindexpath:lastpath Atscrollposition:uitableviewscrollpositionbottom Animated:YES]; }#pragma the data source for the 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 dequeuereusablecellwithidentifier:id]; Cell. Textlabel. Text= Self. Chatmsgs[Indexpath. Row];returnCell } -(void) Scrollviewwillbegindragging: (Uiscrollview*) scrollview{[ Self. ViewEndediting:YES]; }

Eight: Monitor keyboard changes

  //Monitor keyboard[[NsnotificationcenterDefaultcenter] Addobserver: SelfSelector@selector(Kbfrmwillchange:) Name:uikeyboardwillchangeframenotification object:Nil]; }-(void) Kbfrmwillchange: (nsnotification*) noti{NSLog(@"%@", Noti. UserInfo);//Get the height of the form    CGFloatWINDOWH = [UIScreen mainscreen]. Bounds. Size. Height;//keyboard end of frm    CGRectKBENDFRM = [Noti. UserInfo[Uikeyboardframeenduserinfokey] Cgrectvalue];//Get the Y value of the keyboard end    CGFloatKbendy = kbendfrm. Origin. Y; Self. Inputviewconstraint. Constant= Windowh-kbendy; }

IOS Socket Programming

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.