IOS Network Basics

Source: Internet
Author: User

/*------------------------------------Network Fundamentals: 1. Binary data stream--------------------------------*/

<1> Client: Mobile devices (handheld devices such as mobile phones/ipad).

The client is usually front-end/foreground and so on. Ios,android development is front-end development.

<2> server: A machine that provides services to clients (such as data/resources, etc.)---nature is also a computer (+ Server software).

Server development is backend/backend development. Java/php/.net, etc.

<3> Request: The client requests data from the server.

<4> Response (Response): The response of a server to a client request is typically to return data to the client.

Server: According to the development phase, divided into two types:

Remote server: An extranet server. The server to be used by all users after the application is on-line. Speed depends on the user's Internet connection and server performance.

Local server: Intranet server, test server. The server used to develop the test phase. For internal development testers to use. It's fast.

2. The network transmits binary data streams. html/image/Video data ...

How are the binary data streams grouped and transmitted?

}

/*-------------------------------------Network Fundamentals: 2. Seven layer protocol---------------------------------*/

1. Understanding the Network 2. Understanding seven layer Protocol/five Layer Model 3. Understanding sockets.

{

Application layer: Specifies the data format for the "Application".   Http/ftp/email and so on. What does the note say?

Transport Layer: Establishes the communication between "port" and "port". UDP/TCP protocol. " Port ". We'll pass you a note.

Network layer: Determine the location of each computer and establish communication between "host" and "host".   IPV4 protocol, "IP address". The location of the girl

Data Link layer: Determines how 1 and 0 are grouped. Ethernet protocol: A set of electrical signals is a packet. " MAC Address "/network card/broadcast. Affectionate confession

Physical layer: Connect the computer to the network and transmit electrical signals 1 and 0. A piece of white paper

Benefits of the Internet hierarchy:

Changes in the upper layer do not affect the underlying structure at all.

Socket: "Host + port" is "Socket sockets/Sockets"-----TCP/IP protocol

}

/*----------------------------------Network Fundamentals: 3. Packet/Stream----------------------------------*/

1. Understand the packet. 2. Understand the essence of network communication.

{

The basis of network communication: Know each other's MAC address and IP address.

The essence of network communication: exchanging data packets with each other.

Data package:

Each packet contains two parts of "header" and "data". Header "contains some instructions for this packet." Data "is the content of this packet.

Ethernet packet: The most basic packet. The header section contains the MAC addresses, data types, and so on for both sides of the communication. ' Header ' Length: 18 bytes, ' Data ' part length: 46~1500 bytes.

IP packet: The header section contains information about the IP address, protocol version, length, and so on for both sides of the communication. ' Header ' Length: 20~60 bytes, the total length of the packet is 65535 bytes maximum.

TCP/UDP packet: The header section contains both the issuing port and the receive port.  UDP packet: ' Header ' Length: 8 bytes, the total length of the packet is 65535 bytes, just put in an IP packet. TCP packet: Theoretically no length limit, however, in order to ensure the network transmission efficiency, usually does not exceed the IP data length, ensures that a single packet will not be split.

Application Packages: The header section specifies the data format of the application. The data section transmits the specific data content.

Nesting:

The packet layer is nested, and the previous layer of the packet is nested in the data portion of the next layer of packet. Finally, the data is transmitted by the Ethernet packet.

Sub-package/unpacking:

Generally, the data that is passed is large, and the packet is divided into many parts to pass.

Package:

The received packets are stitched together in sequence to form the complete packet.

}

/*----------------------------------Network base: 4.IP address----------------------------------*/

Learn about IP addresses.

{

Static IP Address:

Fixed IP addresses that need to be set manually by the user.

Dynamic IP Address:

An IP address that is automatically generated through the DHCP protocol.

DHCP protocol:

Through the DHCP protocol, the user obtains the native dynamic IP address, the subnet mask, the gateway, the DNS server and so on.

Subnet Mask:

Use with an IP address to determine whether two computers are on the same subnet.

DNS server:

You can convert your domain name (URL) to an IP address.

}

/*----------------------------------Network Fundamentals: 4. An HTTP request--------------------------------*/

Understand the complete process of an HTTP request.

{

1. URL (Uniform Resource Locator):

Uniform Resource Locator. The URL is the address and location of the resource. You can find only one resource on the Internet through a URL.

Basic format of URL: protocol://HOST address/path

Protocol: Different protocols represent different ways to find resources and how to transfer resources.

{

Common protocols in URLs:

<1>http: Hypertext Transfer Protocol, the most commonly used protocol in network development. Access to remote network resources. Format:/HTTP/...

<2>file: When accessing a resource on the local computer. Format: file://(do not add host address)

<3>FTP: Access to the shared host's file resources. Format: ftp://

<4>mailto: The e-mail address is being accessed. Format: mailto:

}

Host Address: The host IP address (domain name) where the resource resides.

Path: The resource is in a specific location on the host.

2. The complete process of the HTTP request:

<1> Request: The client makes the request. Ask for data (operational data) from the server.

<2> response: The server responds to the client's request. Returns the data required by the client.

3. Wrapping an HTTP request

Use Nsurlrequest to wrap an HTTP request. You can specify the cache policy and time-out.

1> Cache Policy selection: Nsurlrequestcachepolicy

{

Nsurlrequestuseprotocolcachepolicy = 0,

The default caching policy, using protocol definitions.

Nsurlrequestreloadignoringlocalcachedata = 1,

Ignore the local cache and download directly from the original server address.

Nsurlrequestreturncachedataelseload = 2,

Download from the original address only if no data exists in the cache

Nsurlrequestreturncachedatadontload = 3,

Only cached data is used, and if no cache exists, the request fails. For offline mode with no network connection

Nsurlrequestreloadignoringlocalandremotecachedata = 4,

Ignore remote and local data caches and download them directly from the original address

Nsurlrequestreloadignoringcachedata = Nsurlrequestreloadignoringlocalcachedata = 1,

Ignore the cache and download it directly from the original server address.

Nsurlrequestreloadrevalidatingcachedata = 5,

Verify that local data and remote data are the same and download remote data if different, otherwise use local data.

}

/*-----------------------------------Network Fundamentals: 5.Socket Walkthrough---------------------------------*/

"Understand" what a socket is.

{

0.

Nc-lk Port number: Always listen for data on this port on the local computer.

1. Import Three header files

{

#import <sys/socket.h>

#import <netinet/in.h>

#import <arpa/inet.h>

}

2.Socket Writing steps

{

1. Create Client socket socket (< #int #>, < #int #>, < #int #>);

2. Create the server socket struct sockaddr_in serveraddress;

3. Connect to the server (socket programming) Connect (< #int #>, < #const struct sockaddr *#>, < #socklen_t #>);

4. Send data to server send (< #int #>, < #const void *#>, < #size_t #>, < #int #>)

5. Receive the data returned by the server recv (< #int #>, < #void *#>, < #size_t #>, < #int #>)

6. Closing the Socket close (socketnumber)

}

/*

Create a client Socket.

Three parameters: domain: Network address types Type: Port type protocal: Transport protocol

Domain: The Protocol field specifies the socket host address type. Network layer Protocol AF_INET/IPV4 Protocol; Af_inet_6/ipv6 protocol

Type: Specifies the socket port type. Specify the Transport Layer protocol type (TCP/UDP), Sock_stream (tcp/stream), Sock_dgram (udp/header)

Protocal: Specify the Transport Protocol: Common protocol: IPPROTO_TCP, IPPROTO_UDP, respectively, corresponding to the TCP transport Protocol, UDP transmission protocol.

The last parameter, 0, automatically selects the protocol corresponding to the second parameter according to the second parameter.

Return value: If > 0 indicates success.

*/

0. Create a client Socket.

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

if (Socketnumber > 0) {

NSLog (@ "Socket creation succeeded:%d", socketnumber);

}else{

NSLog (@ "Socket creation failed");

};

/*

Connect to the server.

Three parameters:

1. Client socket.

2. The receiver's socket parameters.

3. Data length.

Return Value: 0 indicates success, other: error code.

*/

1. Server socket

struct sockaddr_in serveraddress;

IPV4 protocol.

serveraddress.sin_family = af_inet;

The receiver (server) IP address.

SERVERADDRESS.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1");

Port number.

Serveraddress.sin_port = htons (56789);

2. Connect to the server

The data length of the serveraddress.

socklen_t length = sizeof (serveraddress);

Connect to the server.

In the C language, the length of the struct is specified when passing the struct body

& takes the starting position of the data and only passes the length of the data to ensure that the complete structure data is obtained.

Return value: 0 success, others are failures.

int connection = connect (socketnumber, (const struct sockaddr *) &serveraddress,length);

if (!connection) {

NSLog (@ "Connection succeeded%d", connection);

}else{

NSLog (@ "Connection failed");

}

/*

Send a message to the server

Parameters:

1> client socket.

2> Send content address.

3> send content length.

4> send way identification, generally 0.

*/

3. Send a message to the server

Send Message Content

NSString *msg = @ "Hello socket!";

Msg.length: Represents the length of the OC string.

Msg. Utf8string: Converts an OC string to an ASCII code of UTF8, which takes up to 3 bytes in length.

Strlen: Calculates the length of all ASCII codes.

Send Message

ssize_t result = Send (Socketnumber, MSG. Utf8string, strlen (Msg. utf8string), 0);

NSLog (@ "result =%ld", result);

/*

Receiving the message returned by the server

Parameters:

1> client socket.

2> receive content buffers.

3> receives the content buffer length.

4> receive mode. 0 means blocking. You must wait for the server to return data.

return value:

If successful, returns the number of bytes received. Failure returns SOCKET_ERROR

*/

4. The server receives the message

Create a receive content buffer.

uint8_t buffer[1024];

Accept Message

ssize_t len = recv (socketnumber, buffer, sizeof (buffer), 0);

NSLog (@ "Len:%zd", Len);

Remove the data from the accepted content buffer.

NSData *data = [NSData datawithbytes:buffer Length:len];

Converts the binary stream data into a string type.

NSString *receive = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];

NSLog (@ "receive:%@", receive);

5. Close the socket

Close (Socketnumber);

}

IOS Network Basics

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.