Socket network programming and socket network programming

Source: Internet
Author: User

Socket network programming and socket network programming
1. TCP/IP and UDP

TCP/IP (Transmission Control Protocol/Internet Protocol) is an industrial standard Protocol set designed for WANs.
User Data Protocol (UDP) is the Protocol corresponding to TCP. It belongs to the TCP/IP protocol family.
The following figure shows the relationship between these Protocols. TCP/IP protocol families include transport layer, network layer, and link layer:

2. Socket

In Figure 1, we don't see the Socket shadow, so where is it? You can still use graphs to speak clearly.

Socket is an intermediate software abstraction layer for communications between the application layer and the TCP/IP protocol family. It is a group of interfaces. In the design mode, Socket is actually a facade mode, which hides the complex TCP/IP protocol family behind the Socket interface. for users, a set of simple interfaces are all, let the Socket organize the data to conform to the specified protocol.

3. Use socket

Our predecessors have already done a lot for us, and the communication between networks is much simpler, but after all there is still a lot of work to do. I have heard about Socket programming before and think it is a relatively advanced programming knowledge. But as long as I understand the working principle of Socket programming, the mysterious veil will be uncovered.

A scenario in life. You need to call a friend to make a dial-up call. When a friend hears the ringtone and calls the phone, you and your friend can establish a connection to speak. After the communication is over, stop the call. The scenario in life explains this working principle. Maybe the TCP/IP protocol family is born in life, which is not necessarily true.

4. Sample Code
# Import "ViewController. h "# import <sys/socket. h> # import <netinet/in. h> # import <arpa/inet. h> @ interface ViewController () // client socket @ property (nonatomic, assign) int clientSocket; @ property (nonatomic, weak) IBOutlet UIWebView * myWebView; @ end @ implementation ViewController/** ======= Request Header ======== 1> the request line GET/HTTP/1.1 GET indicates "GET" from the server" data/access server root directory HTTP/1.1 HTTP protocol and Version 2> Request Header Host: host User to access- Agent: indicates the type of the server client. Accept: indicates the data format supported by the server client. Accept-Language: indicates the Language supported by the server client. Accept-Encoding: tell the Server Client to support the extract Type HTTP request format, which is a string format, the last line, ended with \ n, indicating that all the request content has been sent and can be processed by the server! Tip: the key value is defined by the HTTP protocol and cannot be changed at will! ============ Response =============1> Status line HTTP/1.1 200 OK HTTP/1.1 HTTP protocol and version 200 status Code (404) 2XX success 4XX client error 5XX Server Error 2> response header, the server tells the client some information prompts: response information, usually used when the "Download" function is developed, date: Response Date: Server Information // file Length: Content-Length: 24 3> data entity, binary data returned from the Server! Println ("hello world! "); */-(Void) viewDidLoad {[super viewDidLoad]; // the http port is 80 if ([self connectToHost: @" 61.135.169.125 "port: 80]) {NSLog (@ "connection successful");} // send a message to the web server // create a request string NSString * request = @ "GET/HTTP/1.1 \ n" "Host: www.baidu.com \ n "" User-Agent: iPhone AppleWebKit \ n "; // processing result NSString * result = [self sendAndRecv: request]; // locate the position where \ r \ n appears, such as "nsange range = [result rangeOfString: @" \ r \ n "]; // determine whether to locate To if (range. location = NSNotFound) {NSLog (@ "html error"); return;} NSString * html = [result substringFromIndex: range. location]; [self. myWebView loadHTMLString: html baseURL: [NSURL URLWithString: @ "http://www.baidu.com"];}-(BOOL) connectToHost :( NSString *) host port :( int) port {// 1. socket/** parameter domain: Protocol domain, AF_INET type: Socket type, SOCK_STREAM (stream TCP)/SOCK_DGRAM (message, tip: programmers in some companies send data to servers, will say: send packets) pr Otocol: IPPROTO_TCP. The prompt is: if 0 is entered, the socket returned by the Protocol is automatically selected based on the second parameter. If the value is greater than 0, the socket is correct */self. clientSocket = socket (AF_INET, SOCK_STREAM, 0); // 2. connect to another computer/** parameter 1> client socket 2> point to the data structure sockaddr pointer, including the destination port and IP address, which has no objects in Language C, all implementations are implemented through struct 3> struct Data Length return value 0 success/other error codes, many C language programs will be designed like this, the reason: There is only one success, there will be many failures! In C, it is usually a non-zero real */struct sockaddr_in serverAddress; // 1> the address inet_addr can convert the ip address to an integer. // The prompt is as follows: A lot of data used on the network requires bytes to flip the serverAddress. sin_addr.s_addr = inet_addr (host. UTF8String); // 2> the port htons can convert the port to an integer // The port number also needs to be converted to a byte flip serverAddress. sin_port = htons (port); // 3> serverAddress protocol. sin_family = AF_INET; // in C, the pointer of the struct is usually passed, and the int result of the struct is passed to connect (self. clientSocket, (const struct sockaddr *) & serv ErAddress, sizeof (serverAddress); return (result = 0);}/*** send & receive message */-(NSString *) sendAndRecv :( NSString *) msg {// 3. sending data to the server/** parameter 1> client socket 2> sending content address 3> sending content length 4> sending method flag, usually 0. If the returned value is successful, the number of bytes to be sent, and the SOCKET_ERROR prompt is returned if the request fails: In many C language frameworks, the basic data type is encapsulated, convenience for subsequent frame adjustment * // In UTF8 encoding, a Chinese character corresponds to three bytes of ssize_t sendLen = send (self. clientSocket, msg. UTF8String, strlen (msg. UTF8String), 0); // 4. receive data from the server Uint8_t buffer [1024]; // 1> defines a variable binary data to facilitate the fight for NSMutableData * dataM = [NSMutableData data]; // The server returns the carriage return count int count = 0; while (count = 0) {// 2> receive data ssize_t recvLen = recv (self. clientSocket, buffer, sizeof (buffer), 0); [dataM appendBytes: buffer length: recvLen]; // by tracking, \ r \ n needs to continue waiting, \ r \ n indicates the end of transmission. // obtain the end byte uint8_t lastByte = buffer [recvLen-1]; // obtain the last and third byte uint8_t preLastByte = buffer [recvLen -3]; if (lastByte = '\ n' & preLastByte! = '\ N') {count ++;} return [[NSString alloc] initWithData: dataM encoding: NSUTF8StringEncoding];}/*** disconnect */-(void) disconnect {// 5. close connection close (self. clientSocket);} @ end
5. Extended reading

1. Linux socket programming:
Http://www.ibm.com/developerworks/cn/education/linux/l-sock/l-sock.html
2. Network Programming Study Note 1: Socket programming:
Http://blog.csdn.net/gneveek/article/details/8699198

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.