HTTP Server and client-05

Source: Internet
Author: User

First of all to give you a preventive needle, this blog more long need you calm down to see. At the same time this blog is also the most important link. How the service and client respond to requests

HTTP Server and Client

The node. JS Standard library provides an HTTP module that encapsulates an efficient HTTP server and a simple HTTP client. http. Server is an event-based HTTP server whose core is implemented by the node. JS downlevel C + + section, and the interface is packaged in JavaScript for high performance and simplicity. Http.request is an HTTP client tool that initiates requests to an HTTP server, such as implementing Pingback or fetching content.

HTTP Server-side

http. Server is an HTTP server object in the HTTP module, and all HTTP protocol-based systems, such as Web sites, social applications, and even proxy servers, are based on HTTP. js. Implemented by the Server. It provides a package of low-level API, just flow control and simple message parsing, all the high-level functions are through its interface to achieve.

http. Events for Server

First, Request: When the client request arrives, the event is triggered, providing two parameters req and res, respectively, HTTP. Serverrequest and HTTP. An instance of Serverresponse that represents the request and response information.

Second, connection: When the TCP connection is established, the event is triggered, providing a parameter socket, which is net. The instance of the Socket. The granularity of the connection event is greater than the request because the client may send multiple requests within the same connection in keep-alive mode.

Third, close: The event is triggered when the server is shut down. Note Not when the user connection is disconnected.

In addition to the checkcontinue, upgrade, and Clienterror events, usually we do not need to care, only when the implementation of the complex HTTP server is used.

Remember how we used to write a service? Http.createserver (FN) FN has two parameters, respectively, req and RESP have the last server listening on port number 3000. In fact, we create a service with a display implementation method.

For example:

var http=require (' http '); var server =new http. Server (); Server.on (' Request ', function (req,res) {         res.writehead (200,{' content-type ': ' text/html '});         Res.write (' 


We're going to go into this service here.

http. Serverrequest

http. Serverrequest is the information for HTTP requests. We are also the most concerned about the service side of the content. We said above that Http.server has a requiest. It generally has http.server requiest event send, as the first parameter, Serverrequest provides some properties as follows:

Complete whether the client request has been sent

Httpversion HTTP protocol version, usually 1.0 or 1.1

Method HTTP request methods, such as GET, POST, PUT, DELETE, etc.

URL of the original request path, such as/static/image/x.jpg or/user?name=byvoid

Headers HTTP Request Header

Trailers HTTP Request Tail (uncommon)

Connection the current HTTP connection socket, which is net. Instance of Socket

Alias for socket Connection property

Aliases for client Client properties

Spoke of HTTP. Serverrequest is the message of the HTTP request, and the HTTPP request can generally be divided into two parts. Oh oh. A request header a request body. may be relatively long as the request body. But we ask not to wait for a long time ah, you suffer a single user can not stand Ah!! , so http. Serverquest provides three events for us to control the transfer of the request body oh oh.

One, data: When the request body data arrives, the event is triggered. The event provides a parameter, chunk, that represents the data received. If the event is not monitored, the request body will be discarded. The event may be called multiple times.

Second, end: When the request body data transfer is complete, the event is triggered, and thereafter there will be no more data to come.

Third, close: The event is triggered when the user's current request ends. Unlike end, if the user forcibly terminates the transfer, it is also called close.

Get the GET Request content

If you're a developer, you know the post and get two common to requests, right? But Http.serverrequest is not like the other Java and PHP have get and post methods Oh oh, here you ask me, that nodejs how to make a GET request? Think about it because get is embedded in the URL, including? The back part, so you can manually parse the contents of the back as the parameters of the GET request. You have to convert the parameters into objects, and of course the conversion section has provided us with the parse module. For example

var http= require (' http '), var url =require (' url '), var util= require (' util '); Http.createserver (function (req,res) { Res.writehead (200,{' content-type ': ' Text/plain '}); Res.end (Util.inspect (Url.parse));}). Listen (3000);


I've added two more methods to the above code. Util.inspect and Url.parse first return the string representation of an object, and the second is to forward the string to a JSON object

In the browser access http://localhost:3000/user?name= ' Heimao ' &age=23 we look at the results oh oh

URL {

Protocol:null,

Slashes:null,

Auth:null,

Host:null,

Port:null,

Hostname:null,

Hash:null,

Search: '? name=%27heimao%27&age=12 ',

Query: {name: ' \ ' heimao\ ', Age: ' 12 '},

Pathname: '/',

Path: '/?name=%27heimao%27&age=12 ',

HREF: '/?name=%27heimao%27&age=12 '}

And then we're just dealing with strings. is not very drag. Query is the content of what we call a GET request. And the path is pathname.

Get POST Request Content

Above, we describe how get is requested. Below we will introduce the second POST request content acquisition. Remember what I said? The HTTP request is divided into two parts, one is the request header and the other is the request body. The HTTP protocol 1.1 version provides 8 standard request methods, the most common of which are GET and POST. Get we're not talking about encoding the content into a URL. The POST request content is all in the request body. Http.serverrequest does not have a property of a request body. The reason for this is that waiting for a request body transfer is a time-consuming task. The customer will be overwhelmed. So to solve this problem, node does not parse the request body by itself. When you need it, we need to parse it ourselves manually. Let's look at an example of how we're going to parse the request body from post.

var http=require ("http"); Varquerystring=require ("querystring"); var util=require ("Util"); Http.createserver (function (req,res) {         varpost= ";         Req.on (' Data ', function (chunk) {                   post+=chunk;         })                   Req.on (' End ', function () {                   post=querystring.parse (post);                   Res.end (Util.inspect (POST))         }). Listen (3000)


Through the above code we can know that node does not parse the data of the post request, but rather through the chunk parameter to cache the data into the post variable inside the last by triggering the end event through Querystring.parse Post to the real POST request format. Then return to the client.

Looking back at what we said above, we're just saying the next three important points one is Http.request events including Data,end,connect. There are two common methods for parsing post and get in Rquest. When we have finished the two methods of the request, we should say Http.serverresponse response mode.

http. Serverresponse

http. Serverresponse is the information returned to the client, which determines the results that the user can eventually see. It is also by HTTP. The Server's request event is sent as a second parameter, generally referred to as response or res

Http.serverresponse has three important member functions for returning response headers, responding to content, and closing requests.

A,response.writehead (StatusCode, [headers]): Sends a response header to the requesting client. StatusCode is an HTTP status code such as 200 (request succeeded), 404 (Not Found), and so on. Headers is an object that resembles an associative array that represents each property of the response header. The function can be called at most once in a request, and a response header is automatically generated if not called.

Response.Write (data, [encoding]): sends the response content to the requesting client. Data is a Buffer or string that represents the content to send. If data is a string, you need to specify encoding to describe how it is encoded, by default, Utf-8. The Response.Write can be called multiple times before the Response.End call.

Response.End ([Data], [encoding]): End the response, informing the client that all sends have been completed. When all the content to be returned is sent, the function must be called once. It accepts two optional parameters, the same meaning and Response.Write. If you do not call this function, the client will always be in a wait state.

We're done talking about the operational methods required by the server. We should now know some of the methods of the client, and then look at the methods that our clients need,

HTTP Client

The HTTP module provides two methods for the client a request and a get, which is a function of requesting the HTTP server as a client.

Http.request

Http.request (options,callback) initiates an HTTP request that accepts two parameters, option is an object of an associative array, represents the request parameter, and callback is the requested callback function.

The detailed configuration of option is as follows:

1) Host: The domain name or IP address of the requesting web site

2) Port: The ports of the requesting Web site, default 80.

3) Methods: The Request method, the default is GET.

4) Path: The relative root path of the request, default is "/". The QueryString should be included. such as Search?query=byvoid.

5) Headers: An associative array object that is the content of the request header.

6) Callback pass a parameter for HTTP. Examples of Clientresponse

7)

And Http.request is returning an instance of a http.clientrequest.

Below is the code that sends the POST request via Http.request

httprequest.js//Import HTTP Module varhttp=require (' http '); Varquerystring=require (' QueryString '); Varcontents=querystring.stringify ({         name: "Blackcat",         email: "[email protected]",                   Address: "Handan, Hebei"}); varoption={         Host: "Www.heimao.com",                   path: "Application/node/post.action",                   Method: "Post",                   headers : {                   "Content-type": "application/x-www-form-urlencoded",                   "content-length": Contents.length         }}varreq= Http.request (Option,function (res) {         res.setencoding (' UTF8 ');         Res.on (' Data ', function (data) {                   console.log (data)         })}); Req.write (contents); Req.end ();


After the run, the results are as follows:
Array (3) {
["Name"]=>
String (6) "Heimao"
["Email"]=>
string "[Email protected]"
["Address"]=>
String (10) "Handan, Hebei"
}

Of course, in addition to the client with a POST request can also be a GET request, you can also put the method in the option to write a get, but node has prepared for us a simpler GET request method. As follows:

Http.get

Second, Http.get (options,callback): It is a simplified version of Http.request, the only difference is that Http.get automatically sets the request method to a GET request and does not require a manual call to Req.end ()

Of course, besides describing the Get method, I have to write a simple demo to make it easier to understand: The demo is as follows:

Varhttp=require ("http"); Http.get ({         host: "Www.heimao.com"},function (res) {         res.setencoding ("UTF8");         Res.on ("Data", function (data) {                   console.log (data);         })})


We have described the client's post and get requests separately, but the parameters of the callback function and the returned objects are still necessary to tell you, we first introduce the next get and post returned object http. Clientrequest.

Http.clientrequest

http. Clientrequest is an object produced by Http.request or http.get that represents an HTTP request that has been generated and is in progress. It provides a response event, which is the binding object of the callback function specified by the second parameter of Http.request or Http.get. We can also explicitly bind the listener function of this event:

var http =require (' http ');
var req =http.get ({host: ' www.byvoid.com '});
Req.on (' response ', function(res) {
Res.setencoding (' UTF8 ');
Res.on (' data ', function (data) {
Console.log (data);
});
});

http. Clientrequest like HTTP. Serverresponse also provides the write and end functions to send the request body to the server, typically for POST, PUT, and so on. After all writes have been completed, the End function must be called to notify the server, otherwise the request is invalid. http. Clientrequest also provides the following functions

1. Request.abort (): Terminates the request being sent. 

2. Request.settimeout (timeout, [callback]): Sets the request time-out period, with a timeout of milliseconds. When the request times out, the callback will be called.

3. In addition, functions such as request.setnodelay ([Nodelay]), request.setsocketkeepalive ([Enable], [InitialDelay]) are also available, see the node. JS documentation for details.

The Http.get () and HTTP are finished. After request returns the Clientrequest object, we repeat the arguments for the second parameter of the Http.get and Http.request callback function http.clientresponse

Http.clientresponse

Similar to the http.serverrequest on the server side, the Clientresponse provides three events date,end and close, which are triggered when the data arrives, the end of the transfer, and the end of the connection, where the data event passes a parameter chunk, which represents the information received.

http. Clientresponse also provides properties that represent the result state of the request,

1) statuscode:http status codes, such as 200, 404, 500

2) httpversion:http protocol version, usually 1.0 or 1.1

3) Headers:http Request Header

4) Trailers:http request tail (uncommon)

In addition to the above properties, several special functions have been shut down as follows

1) response.setencoding ([encoding]): Sets the default encoding, which is encoded with encoding when the data event is triggered. The default value is NULL, which is not encoded and stored as Buffer. Common code is UTF8.

2) Response.pause (): Pause to receive data and send events to facilitate the download function.

3) Response.resume (): Resumes from the paused state.

For more reference addresses:

node. js Manual & documentation:http://nodejs.org/api/index.html.

Understanding Process.nexttick (): Http://howtonode.org/understanding-processnext-tick.

Uncover node. JS Events: http://www.grati.org/?p=318


HTTP Server and client-05

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.