About IOS sockets are here.

Source: Internet
Author: User

Socket (socket) is the cornerstone of communication, is to support the TCP/IP protocol network communication Basic operating unit, contains 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.

Multiple TCP connections or multiple application processes may require data to be transmitted over the same TCP protocol port. To differentiate between the different application processes and connections, the computer operating system provides the socket interface for the application to interact 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.

Establishing a socket connection requires at least one pair of sockets, one running on the client, called Clientsocket, and the other running on the server side, called ServerSocket. The connection between sockets is divided into three steps: Server listening, client request, connection acknowledgement.

The socket can support different transport layer protocols (TCP or UDP), and when connected using the TCP protocol, the socket connection is a TCP connection, and the UDP connection is the same.

The library function used by the socket

1. Creating sockets

Socket(af,type,protocol)//establish contact for address and socket

bind(sockid, local addr, addrlen)//server-side listening client requests

Listen( sockid ,quenlen)//Establish a server/client connection (connection-oriented TCP)

2. Client Request Connection

Connect(sockid, destaddr, addrlen)//server-side waiting for client connection requests to be received from a socket numbered Sockid

Newsockid=Accept(sockid,clientaddr, paddrlen)//Send/Receive Data

3. Connection-oriented:

Send(sockid, buff, bufflen)

Recv( )

4. For no connection:

SendTo(sockid,buff,... ,addrlen)

Recvfrom( )

5. Release sockets

Close(socked)

To send and receive data in iOS with Nsstream (stream), you can set the agent of the stream, change the convection state to make the corresponding action (connection is established, the data is received, the connection is closed).

Nsstream: The parent class of the data stream that defines the abstract attributes, such as opening, closing the agent, Nsstream inheriting from Cfstream (corefoundation)

Nsinputstream:nsstream Subclass for reading input

A subclass of Nsoutputstream:nsstream, used for write output.

The service side does not mention, the client code is probably as follows:

Need to import <arpa/inet.h>,<netdb.h>

- (void)test

{

NSString * Host =@ "123.33.33.1";

NSNumber * Port = @1233;

Create socket

int Socketfiledescriptor = socket(af_inet, sock_stream, 0);

If (-1 = = socketfiledescriptor) {

NSLog(@ "Create failed");

return;

}

Get IP Address

struct hostent * remotehostent = gethostbyname([host utf8string]);

If (NULL = = remotehostent) {

Close(socketfiledescriptor);

NSLog(@ "%@",@ "cannot resolve server hostname");

return;

}

struct in_addr * remoteinaddr = (struct in_addr *)remotehostent h_addr_list[0];

Setting the socket parameter

struct sockaddr_in socketparameters;

Socketparameters. sin_family = af_inet;

Socketparameters. Sin_addr = *remoteinaddr;

Socketparameters. Sin_port = htons([Port intvalue]);

Connecting sockets

int ret = Connect(socketfiledescriptor, struct SOCKADDR *) &socketparameters, sizeof(socketparameters));

If (-1 = = ret) {

Close(socketfiledescriptor);

NSLog(@ "Connection failed");

return;

}

NSLog(@ "connected successfully");

}

This is probably the case, because it is a C language, so it seems not very convenient, general development will use a relatively simple method, as follows.

Cocoaasyncsocket

The socket implementation of iOS is particularly simple and can be simplified with the Open Source class library Cocoaasyncsocket on GitHub, Cocoaasyncsocket is supported for TCP and UMP. The code might look like this:

- (ibaction)connecttoserver:(ID)sender {

1. Connect to the server via three handshake

NSString *host = @ "133.33.33.1";

int Port = 1212;

Create a Socket object

_socket = [[gcdasyncsocket alloc] initwithdelegate: Self delegatequeue :d ispatch_get_global_queue(dispatch_queue_priority_default, 0)];

Connection

Nserror *error = nil;

[_socket connecttohost: Host onPort:p ort error:&error];

If (error) {

NSLog(@ "%@",error);

}

}

#pragma agent for Mark-socket

#pragma Mark connected successfully

-(void)socket:(gcdasyncsocket *)sock didconnecttohost: (nsstring *)host Port:(uint16_t)Port{

NSLog(@ "%s",__func__);

}

#pragma Mark Disconnects

-(void)socketdiddisconnect:(gcdasyncsocket *)sock Witherror :(nserror *)err{

If (err) {

NSLog(@ "Connection failed");

}Else{

NSLog(@ "normal disconnect");

}

}

#pragma mark Data sent successfully

-(void)socket:(gcdasyncsocket *)sock Didwritedatawithtag :(long)tag{

NSLog(@ "%s",__func__);

Manual read after sending data,-1 does not set timeout

[sock readdatawithtimeout:-1 tag: Tag];

}

#pragma mark reads the data

-(void)socket:(gcdasyncsocket *)sock didreaddata:( NSData *)data withtag:(long)tag{

NSString *receiverstr = [[nsstring alloc] initwithdata:d ata Encoding: nsutf8stringencoding];

NSLog(@ "%s%@",__func__,receiverstr);

}

Here is the principle supplement, interested friends can take a closer look.

Network layer Seven Protocol

The network layer Seven protocol consists of 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 referred to as the media layer, which is the object that the network engineer studies, and 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 is oriented to and cares 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, the HTTP protocol is based on the TCP connection, and the three are not comparable in nature. TCP/IP is a Transport layer protocol that mainly addresses how data travels across the network, while HTTP is an application-layer protocol that addresses how data is packaged. The socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, and it is a set of interfaces.

Network layer Seven Protocol

TCP/IP five layer model

The Protocols of the TCP/IP five layer model are: application layer, Transport layer, network layer, data link layer and physical layer. Repeaters, hubs, and the twisted-pair that we usually say also work in the physical layer, bridges (which are now seldom used), Ethernet switches (two-tier switches), network cards (in fact the NIC is half working on the physical layer, half working at the data Link layer) at the data link layer; Routers, layer three switches on the network layer The transport layer is primarily a four-layer switch, and there are routers working on the four level.

The application layer in the TCP/IP protocol handles the functions of layers fifth, sixth, and seventh in the seven-tier model. The transport layer in the TCP/IP protocol is not always guaranteed to reliably transmit packets at the transport layer, and the seven-tier model can do so. The TCP/IP protocol also provides a choice called UDP (User Datagram Protocol). UDP does not guarantee reliable packet transmission.

Correspondence relationship

TCP: For connection-oriented, reliable transmission (guaranteed data correctness, guaranteed data order), for transmitting large amounts of data (stream mode), slow, to establish a connection requires more overhead (time, system resources).

UDP: For non-connected, unreliable transmission, for transmitting small amounts of data (packet mode), fast.

TCP is a flow-mode protocol, and UDP is a datagram-mode protocol.

When transferring data, you can use only the transport layer (TCP/IP), but in that case, the data content cannot be recognized because there is no application layer, and if you want to make the transferred data meaningful, you must use the Application layer protocol (HTTP, FTP, Telnet, etc.) or you can define the application layer protocol yourself.

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 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.

The location of the socket

TCP connections

To understand the socket connection, you need to understand the TCP connection first. Mobile phone can use the network function is because the bottom of the mobile phone implementation of TCP/IP protocol, you can make the mobile phone terminal through the wireless network to establish a TCP connection. 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 enters the Syn_send state, waiting for the server to confirm;

Second handshake: The server receives the SYN packet, it must confirm the customer's SYN (ACK=J+1), and also send itself a SYN packet (syn=k), that is, the Syn+ack packet, when the server enters the SYN_RECV state;

Third handshake: The client receives the server's Syn+ack packet, sends the acknowledgment packet ack (ACK=K+1) to the server, the packet is sent, the client and the server enter the established state, and the handshake is completed three times.

Three-time handshake (three-way handshake) When a TCP connection is established, the client and server are required to send a total of 3 packets. The purpose of the three-time handshake is to connect the server to the specified port, establish a TCP connection, and synchronize the serial number and confirmation number of both parties and Exchange TCP window size information. In socket programming, when the client executes connect (), three handshakes are triggered.

Three-time handshake

The data is not included in the packets that are delivered during the handshake, and the client and server formally begin transmitting the data after the three handshake is complete. 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 disconnection process requires a "four-time handshake".

The removal of the TCP connection requires four packets to be sent, so it is called a four-time handshake (four-way handshake). In socket programming, either side performs a close () operation to generate a handshake (where there is a "wave") operation.

Removal of TCP connections

The difference between a "three-time handshake" and a "four-time handshake" is that the Syn+ack message can be sent directly when the server receives a SYN connection request message from the client side at the end of the connection. Where the ACK message is used to answer, the SYN message is used for synchronization. However, when the connection is closed, when the server side receives the fin message, it is likely that the socket will not be closed immediately, so you can only reply to an ACK message, tell the client side, "You send fin message I received." I can't send fin messages until all the messages on my server end are sent, so I can't send them together. Therefore, four-step handshake is required.

HTTP connection

The HTTP protocol, the Hypertext Transfer Protocol (Hypertexttransfer Protocol), is the foundation of Web networking and one of the most commonly used protocols for mobile networking, an application built on 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." Therefore, the HTTP connection is a "short connection", to maintain the online status of the client program, it is necessary to continuously initiate connection requests to the server. If the server can not receive the client's request for a long time, it is considered that the client "offline", if the client cannot receive a reply from the server for a long time, it is considered that the network has been disconnected. In HTTP 1.0, each request from the client requires a separate connection to be established, and the connection is automatically freed after the request is processed. In HTTP 1.1, multiple requests can be processed in a single connection, and multiple requests can overlap, without waiting for a request to end before sending the next request.

HTTPS (Hyper Text Transfer Protocol over secure Socket Layer) is a security-targeted HTTP channel and is a secure version of HTTP. The SSL layer is added under HTTP, and the security base of HTTPS is SSL, so the details of encryption require SSL. HTTPS has a default port that differs from HTTP and an encryption/authentication layer (between HTTP and TCP). The HTTP protocol sends content in plaintext, does not provide data encryption in any way, and if an attacker intercepts a transmission message between a Web browser and a Web server, it can read the information directly, so the HTTP protocol is not suitable for transmitting sensitive information.

HTTPS protocol requires a certificate to the CA, HTTP is a Hypertext Transfer Protocol, the information is plaintext transmission, HTTPS is a secure SSL Encryption transport protocol, HTTP and HTTPS use a completely different connection, the port is not the same, the former is 80, the latter is 443 The HTTP connection is simple and stateless, and the HTTPS protocol is a network protocol built by the SSL+HTTP protocol that can encrypt transmission and authentication.

HTTPS

The socket connection differs from the HTTP connection

Typically, a socket connection is a TCP connection, so once a socket connection is established, both parties can start sending data content to each other until the two sides are disconnected. In practice, however, the client-to-server communication firewall will turn off a long-inactive connection and cause the Socket connection to be disconnected, 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 at the time of the request, but also to be able to reply to the server after the client has made a request to the server.

About IOS sockets are here.

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.