nodejs 创建http server

来源:互联网 发布:农村淘宝.下载安装 编辑:程序博客网 时间:2024/06/05 10:40

1, http module require: var声明变量,require在引用module的时候,module名字用''引用。

var http=require('http');

2,http的几个方法:

http.createServer([requestListener])#

Returns a new web server object.

The requestListener is a function which is automaticallyadded to the'request' event.


server.listen(port, [hostname], [backlog], [callback])#

Begin accepting connections on the specified port and hostname. If thehostname is omitted, the server will accept connections directed to anyIPv4 address (INADDR_ANY).

To listen to a unix socket, supply a filename instead of port and hostname.

Backlog is the maximum length of the queue of pending connections.The actual length will be determined by your OS through sysctl settings such astcp_max_syn_backlog andsomaxconn on linux. The default value of thisparameter is 511 (not 512).

This function is asynchronous. The last parameter callback will be added asa listener for the'listening' event. See alsonet.Server.listen(port).



3,http.ServerResponse

Class: http.ServerResponse#

This object is created internally by a HTTP server--not by the user. It ispassed as the second parameter to the'request' event.


response.writeHead(statusCode, [reasonPhrase], [headers])#

Sends a response header to the request. The status code is a 3-digit HTTPstatus code, like404. The last argument, headers, are the response headers.Optionally one can give a human-readablereasonPhrase as the secondargument.

Example:

var body = 'hello world';response.writeHead(200, {  'Content-Length': body.length,  'Content-Type': 'text/plain' });

This method must only be called once on a message and it mustbe called before response.end() is called.

If you call response.write() or response.end() before calling this, theimplicit/mutable headers will be calculated and call this function for you.

Note: that Content-Length is given in bytes not characters. The above exampleworks because the string'hello world' contains only single byte characters.If the body contains higher coded characters thenBuffer.byteLength()should be used to determine the number of bytes in a given encoding.And Node does not check whether Content-Length and the length of the bodywhich has been transmitted are equal or not.

response.write(chunk, [encoding])#

If this method is called and response.writeHead() has not been called,it will switch to implicit header mode and flush the implicit headers.

This sends a chunk of the response body. This method maybe called multiple times to provide successive parts of the body.

chunk can be a string or a buffer. If chunk is a string,the second parameter specifies how to encode it into a byte stream.By default theencoding is 'utf8'.

Note: This is the raw HTTP body and has nothing to do withhigher-level multi-part body encodings that may be used.

The first time response.write() is called, it will send the bufferedheader information and the first body to the client. The second timeresponse.write() is called, Node assumes you're going to be streamingdata, and sends that separately. That is, the response is buffered up to thefirst chunk of body.

Returns true if the entire data was flushed successfully to the kernelbuffer. Returnsfalse if all or part of the data was queued in user memory.'drain' will be emitted when the buffer is again free.

response.end([data], [encoding])#

This method signals to the server that all of the response headers and bodyhave been sent; that server should consider this message complete.The method,response.end(), MUST be called on eachresponse.

If data is specified, it is equivalent to calling response.write(data, encoding)followed byresponse.end().

4 小例子

#!/bin/nodejsvar http = require('http');http.createServer(function(req, res){        res.writeHead(404, {                                                                                                                                                                                         'Content-Type' : 'text/plain'        });        res.write("hello, wrold");        res.end();}).listen(3000);console.log("welcome to http's hello world");



0 0
原创粉丝点击