Source code

About Socket, I think this is enough for a few (two) HTTP

In the last article, we preliminarily describes the definition of socket, and the simple use of socket in TCP.

The US is mainly about HTTP related things.

What is HTTP

HTTP -> Hyper Text Transfer Protocol(超文本传输协议) ,它是基于TCP/IP协议的一种 无状态连接

Characteristic

No state

No state refers to, in the standard case, the client sends every request, are independent of the server, and can not get user dialogue directly through the standard HTTP protocol itself in the context of.

Here, many people may have doubts, we usually use HTTP not so ah, we can identify the identity of the server request to login not ah, how do ah?

So the extra explanation, we say the <strong> state</strong> , such as <strong> cookie/session</strong> from the server and the client agreed well, each request when the client server gets to fill in, after the query itself records (database, memory), to determine the identity of the client, and return the corresponding value.

On the other hand to say, the characteristics and the HTTP protocol itself, because the server is not from the protocol itself to obtain the corresponding <strong> state</strong> .

No state can also understand this: <strong> from the same client continuously issued two HTTP request to the server, the server cannot from the HTTP protocol itself gets the relationship between the two request</strong>

No connection

<strong> No connection</strong> refers to the server in response to client requests, take the initiative to disconnect, do not continue to maintain the connection

structure

HTTP is a hypertext transfer protocol, as the name suggests, is a text format transmission, so we describe this protocol format

In HTTP, a very important separator is <strong> CRLF (Carriage-Return Line-Feed)</strong> is <strong> /r</strong> + <strong> /n</strong> returns a newline, it is used as the character recognition

Request Request

 Request format

The request format

The request line

GET / HTTP/1.1/r/n

The first line is also called the request line, is used to tell the server, a client call <strong> request type</strong> , <strong> request path</strong> , <strong> request protocol type</strong>

<strong> The type of request</strong> is what we often say that (the interviewer asked the <strong> GET</strong> , <strong> POST</strong> and so on) to send the position, it is located in the beginning of the request

Request resource path Is to provide the address path inside the server, the server client wants to tell what access to resources, access in the browser Www.jianshu.com/p/6cfbc63f3... (with Jane books for a wave of demonstration, is our request) /p/6cfbc63f3a2b

<strong> Request protocol type</strong> use at present most is <strong> HTTP/1.1,</strong> perhaps in the near future, will be replaced by <strong> HTTP/2.0</strong>

Note:

  1. The link for the HTTPS link, but the content of HTTP and the like, so the use of the link as an example, SSL will be described in the next few articles in

  2. Request for different content need to use <strong> "spaces</strong> to do segmentation

  3. For the end of the line to add <strong> CRLF</strong> separator

The first request Request Headers

The request line, until the request body (body), between the part, we become the first request.

Request the length of the header is not fixed, we can place an unlimited number of content to the request header.

But the request header format is fixed, we can take it as the key to.

Format:

 Key: Value /r/n

We usually say <strong> cookie</strong> is the head of a request

Some commonly used HTTP the definition and function of: Blog.csdn.net/philos3/art...

Note:

When the head is over all requests (that is, we want to send body) when we need to add an extra blank request header tells the server (<strong> CRLF</strong> ) has come to an end

Request Body request body

If we use header not so much chance, then body is almost every developer must contact.

Usually, when we make the POST request parameters we uploaded here.

The server is how to get the full Body we upload? In other words, how do we know that the body server is already transmitted over?

If we think about it, when we need to implement this agreement, what would we do?

  • Can contract the special byte as termination characters, when read into the specified character, that read

  • The sender must know the size of the data to be transmitted, tell the receiver, receiver only need to receive the specified size data can stop receiving

  • The sender does not know the size of the data (or he needs to spend a lot of cost in order to know the size of the data), the first to tell the receiver, I do not know how many times, such as sending, sending the real time to tell the recipient, "this time I want to send the number", finally told the recipient, "I sent." to stop receiving the receiver. "

Perhaps you will have other ideas, congratulations to you, you can achieve a similar reception method.

At present, the server is to rely on the above three methods received:

  • Agreed special byte:

The client in sending the data, call off the socket connection, the server parses the data received in the closing request, and returns the result, then closes the connection

  • To determine the size of the data:

In the client Request header In a given field Content-Length The server to the corresponding data analysis, after receiving body, when the body data reaches the specified length, the server to parse the data and returns the result

  • Uncertain data size (Http/1.1)

In the client Request header In the given head Transfer-Encoding: chunked Then, start sending data

Each section of data transmission has a specific format,

Format:

  1. Line length:

Each piece of data at the beginning of the text for this section of <strong> the real data sent 16 hexadecimal length</strong> plus <strong> CRLF</strong> delimiter

  1. Data line:

<strong> The real data sent</strong> with <strong> CRLF</strong> separator

Cases:

 Twelve /r/n / / line length in base 16 is 12 in base 10, 18
It Is A chunk Data /r/n CRLF delimiter / / data line

At the end of period:

Complete to tell the server to parse the data sent or stored data.

At the end of a fixed format

 0/r/n
/r/n

At present, the client using this method is not much.

Here, how to tell the server should receive how many pieces of data have been completed

Coming up next, tell what is the data server.

The head is also defined: Content-Type

Content-Type: Blog.csdn.net/qq_23994787...

Here, the basic format of Request has been finished

In response to Response

 Response format

The corresponding structure

In fact, Response and Request from the protocol analysis, they are the same, but they are on the Http protocol in different implementations of the text of the agreement.

Response line

HTTP/1.1 200 OK/r/n

The first line is called the <strong> response line</strong> , is used to tell the client request processing status, by <strong> request protocol type</strong> , <strong> server status code</strong> , <strong> the corresponding state description</strong> form

<strong> Request protocol type</strong> is used to tell the client and server using the protocol is what, for the client the following processing.

<strong> The server status code</strong> is a very important return value, it is used to inform the server to the client request processing results.

The status code is very much, but for our development is generally used is the following code

Status code The corresponding state description Meaning Customer operation
Two hundred OK Mark the request by the server successfully processed nothing
Four hundred Bad Request Marks the client request problem, the server does not recognize, client server can be modified for processing Modify the request parameters
Four hundred and one Unauthorized The need to check permissions for the current request, the client needs to submit the corresponding authority at the next head request information Modify the Header header and submit corresponding information
Four hundred and three Forbidden The request was rejected by the server to perform (firewall to block or other reasons) For a period of time after the re launched, no other solution
Four hundred and four Not Found Service cannot find the corresponding resources (the most common error code) Modify the Request resource request path
Four hundred and five Method Not Allowed The current client request method not allowed Modification request method
Four hundred and eight Request Timeout A client request timeout (the server is not within the time allowed to parse out the entire Request) Re request
Five hundred Internal Server Error The server itself (probably not error of abnormal operation in the process of processing) Contact the back-end developers (anyone who says this is to solve client problems went to his theory)

Please refer to the complete error code: Baike.baidu.com/item/HTTP state...

<strong> In response to Response Headers head</strong> and <strong> the body of the Response response Body</strong>

These contents and <strong> Request</strong> in the corresponding part of no difference, did not repeat


We have two parts from the characteristics and structure about Http related attributes, the main contents of this article here is basically over, then I want to talk about some other HTTP related knowledge

Cross domain

As the mobile terminal developers, we don't know much about this, are hardly used, but I still need to explain here. Because now we have to end time, in case we need to set foot in front after understanding, cross domain, at least can solve many things for us.

This article will explain in detail how to solve the problems of cross domain, the reason will only explain the formation of cross domain

What is cross domain

In cross domain, need to talk about what is the <strong> domain</strong>

What is the domain

In the process of socket on the last lesson, we have found that want to establish a connection TCP/IP need to know at least two things

  1. The other side of the address (host)

  2. The other number (port)

We can only rely on the establishment of the two TCP/IP host connection, which indicate how we find each other, port said, we should connect to that port specific.

The application server is always in listening to this port, so as to ensure that when there is a link to the server, a direct response to the corresponding information

To talk about it, we usually say the server refers to the <strong> application server</strong> , for example, say Tomcat, Apache and so on, they start when bound a designated port (usually not at the same time bound two ports). So, as a client, you can use <strong> host+port</strong> to determine whether a specified <strong> server application</strong>

Thus, the concept of this <strong> domain</strong> is generated, <strong> host</strong> + <strong> port</strong>

For instance: Http://127.0.0.1:8056/

This site belongs to the domain of <strong> 127.0.0.1+8056</strong> can also be written as <strong> 127.0.0.1:8056</strong>

Someone will ask, that <strong> localhost:8056</strong> and <strong> 127.0.0.1:8056</strong> are of the same domain, they are equivalent.

They do not belong to the same domain, prescribed is dead, because their host expression is different, so it is not.

Cross domain

We already know the domain, the cross domain also appeared, is a <strong> domain</strong> access to another <strong> domain</strong> .

We can see from the HTTP protocol, the server is not mandatory for any domain, that is to say, do not care about this visit is to visit the server from which domain, at the same time, as the client, we did not say this domain.

So what is the <strong> cross domain</strong> ?

This is to say that the source of cross domain, our daily access to the site, it is actually the HTML code, the code will be sent to the server by the browser, the browser to render and show us.

The development of browser programmers in the development, the "do not know exactly what to do, but they can't give" for the sake of safety, and the client (socket) the same privileges, so they restrict some operation in the <strong> domain</strong> of "some of the requested operation on the other side of the server is not allowed to add the <strong> domain</strong> . Access time, access operation will not be executed, the operation of the browser security has a great influence to the.

So in cross domain.

Cross domain from A to Z are just a client operation behavior, from a certain angle, it has no relationship with the server, because the server cannot know whether a request from a web page (the client does not fit the situation), will be banned

For our understanding of the mobile terminal, we can at least say after the cross domain, cross domain has nothing to do with us -_-

Socket to achieve a simple HTTP request

In fact, an article without code support, just pure concept elaboration, still feel the shortcomings of what, this article will do some small improvements in the code on the basis of.

Here with rookie network HTTP tutorial tutorial as this article test ( Www.runoob.com/http/http-t... ) (ip:47.246.3.228:80)

 / / MARK: Create establish
Let socketFD = Darwin.socket (AF_INET, SOCK_STREAM, Zero )

Func converIPToUInt32 (a: Int B:. Int C:. Int D:. Int {- > in_addr)
     Return Darwin.in_addr s_addr: (__uint32_t ((a < < Zero The | (b) Eight The | (c) Sixteen The | (d) Twenty-four )))
}
/ / MARK: Connect Connect
Var Sock4: = sockaddr_in (sockaddr_in)

Sock4.sin_len = __uint8_t (MemoryLayout.size (ofValue: sock4))
/ / convert IP to UInt32
Sock4.sin_addr = converIPToUInt32 (a: Forty-seven B:. Two hundred and forty-six C:. Three D:. Two hundred and twenty-eight )
Because of / / bytes of memory and network communication bytes instead, Gu we need to exchange the port which is connected with the end of our size Eighty
Sock4.sin_port = CFSwapInt16HostToBig ( Eighty )
Set the sin_family to AF_INET / / says that this is IPv4 connection
Sock4.sin_family = sa_family_t (AF_INET)
/ / Swift pointer strong to OC complex
Let pointer: UnsafePointer (= withUnsafePointer To &sock4, {$ Zero (withMemoryRebound To : sockaddr.self, Capacity : One {$. Zero }}))

Var  Result = Darwin.connect (socketFD, pointer, socklen_t (MemoryLayout.size (ofValue: sock4)))
Guard  Result =! -1  Else {
(fatalError "Error in connect (function) code / is (errno)" )
}
/ / assembly text protocol access rookie tutorial Http Course
Let = sendMessage "GET /http/http-tutorial.html HTTP/1.1/r/n"
+ "Host: www.runoob.com/r/n"
+ "Connection: keep-alive/r/n"
+ "USer-Agent: Socket-Client/r/n/r/n"
/ / convert binary
Guard Let Data (= sendMessage.data Using :.Utf8) Else {
(fatalError "Error occur when transfer to data" )
}
/ / pointer conversion
Let = data.withUnsafeBytes ({UnsafeRawPointer ($dataPointer Zero }))

Let Status = Darwin.write (socketFD, dataPointer, data.count)

Guard  Status =! -1  Else {
(fatalError "Error in write (function) code / is (errno)" )
}
/ / set Thirty-two Kb bytes of storage to prevent overflow
Let = readData Data ( Count : Sixty-four * One thousand and twenty-four )

Let readPointer = readData.withUnsafeBytes ({UnsafeMutableRawPointer ($mutating: Zero }))
How many bytes read / recording current
Var = currentRead Zero

While  True {
/ / read socket data
Let Result = Darwin.read (socketFD, readPointer + currentRead, readData.count - currentRead)

     Guard  Result > Zero  Else {
(fatalError "Error in read (function) code / is (errno)" )
}
Here is to reduce the call frequency / sleep
     Sleep ( Two )
     If  Result = = Zero {
(print "No new data" )
Continue
}
The latest data read / / record
= currentRead Result
/ / print
(print String ( Data : readData, Encoding :.Utf8)?? "" )

}

The corresponding code examples have been put on the GitHub: Github.com/chouheiwa/S...

summary

The more the less I know about, we now walk every step is in learning.

Topic: drawing good hard ah, is a painting by PPT -_-

Author: chouheiwa
Link: https://juejin.im/post/5c4ff9236fb9a04a060544ef

Fabulous ( Zero )

This paper consists of Contributors This paper addresses the creation: Https://blog.isoyu.com/archives/guanyusocketkanwozhejipianjiugouleerzhihttp.html
Use Creative Commons 4 The international license. In addition to indicate the transfer / origin, are the original or translation, please be sure to sign before reprint. The final edit time: 2 1, 2019 at 06:55 PM

Lively article

Comment:

1 comments, visitors: 1, bloggers: 0

Comment

[required]

See?

Please wait for 3 seconds after the submission to avoid submitting the success and repeat