Overview

更新时间:
2024-04-03
下载文档

Overview

The http module provides basic http protocol support and includes the following features:

  • Basic http server
  • Basic http client

This document focuses on the use of HttpServer. HttpServer supports http and https. http protocol versions are HTTP/1.1. A single server can be created, and a server group (mult-task mode) is also allowed.

User can use the following code to import the http module and access HttpServer .

var http = require('http');

Support

The following shows http module APIs available for each permissions.

 User ModePrivilege Mode
http.createServer
http.createSubServer
server.isMaster
server.groupName
server.addcert
server.start
server.stop
server.port

HttpServer Class

The HttpServer inherit from Server. It can be create by createServerand createSubServer.

http.createServer(group, handle, subs[, subMode], saddr[, tlsOpt])

  • group {String} Server group name(master server module). Usually the module name is used as the group name. If the server work on mult-task mode(subs > 0) and subMode is missing, the group must be supported as app module name.
  • handle {Function} Http request handle function.
  • subs {Integer} The new task counts, if subs > 0, server run in mult-task.
  • subMode {String} sub-server module. If the sub-server is the same module as the master-server, subMode can be defaulted and provided by group. Otherwise, subMode represents the sub-server module.
  • saddr {Object} Server socket address. If the port of saddr is set to 0, the setting port will be assigned automatically, and the port can be found through server.port().
  • tlsOpt {Object} TLS securely connections options. default: undefined, means use TCP connection.

This method creates a master-server. When the master-server starts, it can create a specified number(subs) of sub-servers (subs), refer to HttpServer mult-task.

Example

  • Create single server:
var HttpServer = require('http').HttpServer;

var saddr = socket.sockaddr(socket.INADDR_ANY, 8000);
var httpSer = HttpServer.createServer('./http_server', function(req, res) {
  res.end('hello world.');
}, 0, saddr);

httpSer.start();
  • Create mult-task server:
var HttpServer = require('http').HttpServer;

var saddr = socket.sockaddr(socket.INADDR_ANY, 8000);
var httpSer = HttpServer.createServer('./http_server', function(req, res) {
  res.end('hello world.');
}, 2, saddr);

httpSer.start();

http.createSubServer(group, handle)

  • group {String} Server group name, the same as master-server group name.
  • handle {Function} Http request handle function.

Use this method to create a sub-server when the sub-server is not on the same module as the master-server.

Example

  • Master-server, ./http_mult.js:
var HttpServer = require('http').HttpServer;

var saddr = socket.sockaddr(socket.INADDR_ANY, 8000);
server = HttpServer.createServer('http_mult', function(req, res) {
  res.end(`my ser is: ${server.groupName.name}`);
}, 2, './http_mult_sub', saddr);

server.start();
  • Sub-server, ./http_mult_sub.js:
var HttpServer = require('http').HttpServer;

var server = HttpServer.createSubServer('http_mult', function(req, res) {
  res.end(`my ser is: ${server.groupName.name}`);
});

server.start();

HttpServer mult-task

The HttpServer have two work mode:

  • MASTER The master-server listens and receives the client request. If the sub server is registered on the master server, the master server will dispatch the request to itself or the sub server for processing.

  • SUB The sub-server works on a separate task. It does not listen on the port, does not directly accept requests from the client, but accepts requests dispatched by the master-server.

A httpServer can be a single task or multiple tasks(mult-task). When it works in mult-task mode, there is one master-server and several sub-servers, which are created by master-server when the master-server is started. When the master-server is working, the client requests are evenly distributed to all the sub-servers and the master-server itself.

The sub-server can be the same module as the master-server, or it can be a different module. If they are on the same module, you don't need to create a sub-server explicitly. If the sub-server is not on the same module as master-server, user should create it by createSubServer.

HttpServer Object

server.isMaster()

  • Returns: {Boolean} Whether it is the master server.

Get whether the server object is the master server.

server.groupName

  • groupName {Object}
    • group {String} The server group name, see HttpServer mult-task.
    • name {String} The server name, see HttpServer mult-task.

server.addcert(opt)

  • opt {Object} Tls server option.
  • Returns: {Boolean} Whether it was added successfully.

opt includes following items:

  • name {String} Server domain name.
  • ca {String} Optional trusted CA certificates. default: no CA certificates.
  • cert {String} Server certificate.
  • key {String} Private key of server certificate.
  • passwd {String} Private key password. default: no password.

This method adds a SNI (Server Name Indication) certificate to the tls server. SNI is an extension used to improve SSL or TLS for servers. It mainly solves the disadvantage that one server can only use one certificate (one domain name). With the support of the server for virtual hosts, one server can provide services for multiple domain names, so SNI must be supported to meet the demand.

server.start()

  • Returns: {Boolean} Server start success or not.

Start http server.

server.stop([stopAll] [, cb])

  • stopAll {Boolean} always true for MASTER mode, close all task servers. For SUB mode: true - stop all task servers; false - stop this sub server. default: false.
  • cb {Function} Callback when stop event emit.

Stop http server.

server.port()

  • Returns: {Integer | Undefined} Server socket port.

When the server starts with the MASTER module, server.port() gets the port of the server, otherwise it returns undefined.

Example

var port = server.port();
console.log(port);

HttpServer Events

start

Emitted when the http server start done.

stop

Emitted when the http server stop.

request

Emitted when a http request comes to server. It has the following properties:

  • req {HttpServerRequest} The http request object, see HttpServerRequest.
  • res {HttpServerResponse} The http response object, see HttpServerResponse.

HttpServerRequest Object

HttpServerRequest inherit from HttpInput class, see the HttpInput module for more details: : HttpInput.

request.enableTimeout(enable)

  • enable {Boolean} The request session timeout option. default: true.

If request enable timeout (req.enableTimeout(true)), the server does not track the request session until the client closes the HTTP connection or an exception occurs. Otherwise, the server will trace the request and the server will close the HTTP connection with the request timed out.

Example

req.enableTimeout(false);

request.close()

Close the request session and close HTTP connection.

request.destroy([error])

  • error Error which will be passed as payload in 'error' event.
  • Returns: this.

Close the request session and close HTTP connection.

HttpServerRequest Events

data

When HTTP body is received from the client a data event is emitted with a buf object:

  • buf {Buffer} Receive from client.

end

When all body data is received or there is no body data a end event is emitted.

close

A close event is emitted when the request disconnected. Request may be closed normally or not properly, so the end event may not be emitted before the close event.

error

A error event is emitted when the error occurs.

HttpServerResponse Object

HttpServerResponse inherit from HttpOutput class, see the HttpOutput module for details: HttpOutput.

response.destroy([error])

  • error Error which will be passed as payload in 'error' event.
  • Returns: this.

Close the response session and close HTTP connection.

HttpServerResponse Events

end

A end event is emitted when the response had been done. The follow method will emitted 'end' event:

  • res.end()

finish

The output stream finishs. The finish event is the same as the end event.

close

A close event is emitted when the response disconnected. Response may be closed normally or not properly, so the end or finish event may not be emitted before the close event.

error

A close event is emitted when the error occurs.

drain

If a call to res.write(chunk) returns false, the 'drain' event will be emitted when it is appropriate to resume writing data to the response.

Example

  • Base http server
var socket = require('socket');
var HttpServer = require('http').HttpServer;
var iosched = require('iosched');

var saddr = socket.sockaddr(socket.INADDR_ANY, 8000);
var server = HttpServer.createServer('./base_httpserver', function(req, res) {
  res.end('Hello world.');
}, 0, saddr);

server.start();
while(true) {
  iosched.poll();
}
  • Mult-server Http master-server and sub-server the same module:
var socket = require('socket');
var HttpServer = require('http').HttpServer;
var iosched = require('iosched');

var count = 0;
function handle(req, res) {
  var content = `
  <html>
    <head>
      <link rel="icon" href="data:image/ico;base64,aWNv">
    </head>
    <body>
      <H1>This is sub server</H1>
      <H2>my ser is: ${server.groupName.name}</H2>
      <H2>ser count: ${count++}</H2>
    </body>
  </html>`;

  res.setHeader('Content-Type', 'text/html');
  res.end(content);
}

var saddr = socket.sockaddr(socket.INADDR_ANY, 8000);
var server = HttpServer.createServer('./http_multserver', handle, 2, saddr);

server.start();
while(true) {
  iosched.poll();
}
  • Mult-server different module

    • master-server module, ./http_mult.JS:
    var socket = require('socket');
    var HttpServer = require('http').HttpServer;
    var iosched = require('iosched');
    
    var count = 0;
    function handle(req, res) {
      var content = `
      <html>
        <head>
          <link rel="icon" href="data:image/ico;base64,aWNv">
        </head>
        <body>
          <H1>This is master server</H1>
          <H2>my ser is: ${server.groupName.name}</H2>
          <H2>ser count: ${count++}</H2>
        </body>
      </html>`;
    
      res.setHeader('Content-Type', 'text/html');
      res.write(content);
      res.end();
    }
    
    var saddr = socket.sockaddr(socket.INADDR_ANY, 8000);
    var server = HttpServer.createServer('http_mult', handle, 2, './http_mult_sub', saddr);
    
    server.start();
    while(true) {
      iosched.poll();
    }
    
    • sub-server module, ./http_mult_sub.js:
    var HttpServer = require('http').HttpServer;
    var iosched = require('iosched');
    
    var count = 0;
    function handle(req, res) {
      var content = `
      <html>
        <head>
          <link rel="icon" href="data:image/ico;base64,aWNv">
        </head>
        <body>
          <H1>This is sub server</H1>
          <H2>my ser is: ${server.groupName.name}</H2>
          <H2>ser count: ${count++}</H2>
        </body>
      </html>`;
    
      res.setHeader('Content-Type', 'text/html');
      res.end(content);
    }
    
    var server = HttpServer.createSubServer('http_mult', handle);
    
    server.start();
    while(true) {
      iosched.poll();
    }
    
文档内容是否对您有所帮助?
有帮助
没帮助