iOS Learning--socket

Source: Internet
Author: User

To understand the socket, you need to understand how the data travels across the network.

Network communication has three elements: IP address, the representation of devices in the network, For example, the machine with 127.0.0.1, or with the name: localhost; port number, used to identify the logical address of the process, that is, the service, the effective port 0~65535, generally 1024 the following ports are occupied by the system or local services, in the development as far as possible, not to use in order to avoid conflict; communication protocol-- UDP,TCP,UDP is a user data message protocol that only sends data and does not establish a join regardless of whether it is received or not, and it encapsulates the data and purpose in the packet. Each packet size is within 64K, the data transfer speed is very fast, but it is not safe, generally used in the game, broadcast and other industries; TCP needs to establish a connection to transfer data, do not limit the size of the data, need to pass three handshake protocol to complete the link, safe and reliable, the disadvantage is inefficient.

Three-time handshake to establish the connection:

  

First the client sends a connection request to the server, the server agrees to send an ACK message and allocates resources for the connection, and after the client receives the ACK message, it sends an ACK message to the server and allocates resources for the connection so that the TCP connection is successful. When disconnected, the four-time Wave protocol is used:

Client sends a disconnect request, fin message, the server receives fin message, know that the client is ready to end the connection, no longer transmit data, but if the server side is not ready, do not worry about shutting down Scoket, can still send data to the client, In this case, you need to send an ACK message, tell the client to wait for the end, let the client into fin_wait state. When the server determines that the data is sent and can be shut down, sending the fin message into the client,client receives the fin message, it does not disconnect immediately, in order to avoid the wrong shutdown state, such as the server does not intend to shut down the connection, will send an ACK message to the server, and will enter the Time_ Wait status, waiting for 2MSL to not receive the server back strain formally disconnected, and the server after receiving an ACK message will also be disconnected.

UDP involves data packaging and sending, which requires an understanding of the OSI seven layer model:

  

For data transmission, the first application layer to form a source, and then in the transport layer through the TCP/UDP protocol packaging, in the network layer, determine the IP and port number (form socket), establish data transmission IO, data link layer packaging data, each packet of data is a frame, and finally through the physical layer to electrical signals, The transmission of electrical signals using high and low levels, in fact, is 01 of data, that is, binary data transmission, so the network data transmission form is binary.

Once you know so much, look at the socket concept. Network communication is the socket between the communication, need both ends are sockets, and then the two ends to establish IO transmission. It can be understood that the socket is a network mechanism class, the specific information that is instantiated is the ip+ port. When we use QQ chat, a mobile phone IP+QQ port to send information, you need to find the B-cell phone IP+QQ port to receive data;

The socket itself is written in C language, convenient for cross-platform use, it is also very simple to use, the basic can be returned to five steps. Step, create socket, second step, build connect, third step, write data, fourth step read data, fifth step colse;

  

First, open the terminal, enter the command: NC-LK 1025 (listening port number 1025)

Import Header file:

  

#import <sys/socket.h>#import <netinet/in .h>#import <arpa/ Inet.h>

To create a socket connection by operation:

1. Create a socket

  

/* *     parameter     Socket three parameters passed in the corresponding value domain     :    protocol field, Af_inet, IPV4 af_inet6, IPV6     type:      socket Type, SOCK_STREAM data stream/sock_dgram data packet     protocol:ipproto_tcp, if passed in 0 then automatically chooses the appropriate protocol return value according to the second parameter     socket      */    int0);

2. Connect to the server

    /** parameter 1> client socket 2> Pointer to data structure SOCKADDR, including destination port and IP address 3> structure data length return value 0 success/Other error code */    structsockaddr_in severaddr; Severaddr.sin_family=af_inet; //PortSeveraddr.sin_port = htons (1025); //AddressSEVERADDR.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1"); intConnresult = Connect (Clientsocket, (Const structSOCKADDR *) &severaddr,sizeof(SEVERADDR)); if(Connresult = =0) {NSLog (@"Connection Successful!!"); }Else{NSLog (@"failed%d", Connresult); return; }

3.write data, write Hello world can see the corresponding display on the simple port

  

/* *     parameter     1> client socket     2> send content address     3> Send content length     4> send way flag, typically 0     return value     if successful, Returns the number of bytes sent, and fails to return     socket_error    */* sendmsg =@ "Hello World " ;     0);

4.read data, write me too on port to see Xcode print results show

  

   /* *     parameter     1> client socket     2> receive content buffer address     3> receive content cache length     4> receive mode, 0 indicates blocking, must wait for server return data     return value     If successful, returns the number of bytes read in, and the failure returns     Socket_error */     uint8_t buffer[]; // Get the space ready! sizeof 0);          

5. The end is to close the socket

Close (Clientsocket);

iOS Learning--socket

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.