HttpServer

Moduleejs.web
Definitiondynamic class HttpServer
InheritanceHttpServer inherit Object
Specifiedejscript-2.5
StabilityEvolving.

HttpServer objects represents the server-side of Hypertext Transfer Protocol (HTTP) version 1.1 connections.

The HttpServer class is used to receive HTTP requests and generate responses. It supports the HTTP/1.1 standard including methods for GET, POST, PUT, DELETE, OPTIONS, and TRACE. It also supports Keep-Alive and SSL connections.


Properties

QualifiersPropertyTypeDescription
static PrunePeriod Frequency to check and release excess worker threads 0.
get addressStringGet the local IP address bound to this socket.
get set asyncBooleanThe current async mode.If the server is put into sync mode, it must be done before calling listen. Set to true if the stream is in async mode.
configObjectServer configuration. Initially refers to App.config which is filled with the aggregated "ejsrc" content. If a "ejsrc" configuration file exists, it is loaded once at startup and is blended (overwrites) existing App.config settings.
documentsPathDefault local directory for web documents to serve. This is used as the default Request.dir value.
homePathDefault root directory for the server. The app does not change its current directory to this path.
get set hostedBooleanFlag indicating if the server is running hosted inside a web server.
static indiciesArrayIndex files list. Index files are used by various handlers when requests to directories are made. The indicies are tried in turn for the first valid index file.
get isSecureBooleanFlag indicating if the server is using secure communications. This means that TLS/SSL is the underlying protocol scheme.
get limitsObjectResource limits for the server and for initial resource limits for requests.
get set nameStringThe authorized public host name for the server. If defined, this name will be used in preference for request redirections. If no name is defined, redirections will use to the listening IP address by default.
optionsBooleanHttpServer constructor options.
onrequest Function to invoke inside a worker when serving a threaded request. The function is invoked with the signature: function onrequest(request: Request): Void.
get portNumberGet the port bound to this Http endpoint.
get softwareStringSoftware description for the web server.

HttpServer Class Methods

QualifiersMethod
static create(address: String, options: Object = expression): Void
 Convenience routine to create a web server.

HttpServer Instance Methods

QualifiersMethod
HttpServer(options: Object = expression)
 Create a HttpServer object.
accept(): Request
 Accept a new incoming for sync servers.
close(): Void
 Close the stream.
listen(endpoint: String = null): Void
 Listen for client connections.
off(name: Object, observer: Function): Void
 Remove an observer from the server.
on(name, observer: Function): HttpServer
 Add an observer for server events.
passRequest(request: Request, worker: Worker)
 Pass a request into a worker VM.
process(app: Function, request: Request, finalize: Boolean = true): Void
 Process a web request.
pruneWorkers(): Void
 Prune idle worker threads.
run(): Void
 Run the application event loop to service requests.
secure(keyFile: Path, certFile: Path, protocols: Array = null, ciphers: Array = null): Void
 Define the Secure Sockets Layer (SSL) protocol credentials.
serve(request: Request, router: Router = expression): Void
 Serve a web request.
setLimits(limits: Object): Void
 Update the server resource limits.
setPipeline(incoming: Array, outgoing: Array, connector: String): Void
 Define the stages of the Http processing pipeline.
setWorkerImage(worker: Worker): Void
 Define a worker that will serve as the base for cloning workers to serve web requests.
trace(options: Object): Void
 Configure request tracing for the server.
verifyClients(caCertPath: Path, caCertFile: Path): Void
 Verify client certificates.

Method Detail

ejs.web HttpServer(options: Object = expression)
Description
Create a HttpServer object. The server is set to async mode by default. If an "ejsrc" file exists in the server root, it will be loaded.
Parameters
options: Object Set of options to configure the server. [default: expression]
options: Object null [default: expression]
Options
documentsDirectory containing web documents to serve. If unset and the HttpServer is hosted, the documents property will be defined by the web server.
homeBase directory for the server and the "ejsrc" configuration file. If unset and the HttpServer is hosted, the home property will be defined by the web server.
ejsrcAlternate path to the "ejsrc" configuration file.
configAlternate App.config settings.
unhostedIf hosted inside a web server, set to true to bypass any web server listening endpoints and create a new stand-alone (unhosted) listening connection.
Specified
ejscript-2.5
Stability
Prototype.
Example
let server: HttpServer = new HttpServer({documents: "web"})
let router = Router(Router.Restful)
server.on("readable", function (event: String, request: Request) {
    // "this" object is also set to request
    request.status = 200
    request.setHeaders({"Content-Type": "text/plain"})
    request.on("readable", function (event, request) {
        let data = new ByteArray
        if (request.read(data) == null) {
            print("EOF")
        }
    })
    request.on("writable", function (event) {
        request.write("Hello World")
        request.finalize()
    })
}
server.listen("127.0.0.1:7777")

accept(): Request
Description
Accept a new incoming for sync servers. This call creates a request object in response to an incoming client connection on the current HttpServer object. In async mode, the accept() call is not needed as the HttpServer automatically creates the Request object and passes it on "readable" events.
Events
IssuesA "accept" event when there is a new connection available.
Returns
A Request object if in sync mode. No return value if in async mode.
Example
server = new HttpServer
server.listen("8080")
while (request = server.accept()) {
    server.serve(request)
}

close(): Void
Description
Close the stream.
Events
closeA close event is issued before closing the stream.

static create(address: String, options: Object = expression): Void
Description
Convenience routine to create a web server. This will start a routing web server that will serve a variety of content using the given specified route tables.
Parameters
address: String The IP endpoint address on which to listen. The address may be a port number or a composite "IP:PORT" string. If only a port number is provided, the socket will listen on all interfaces on that port. If null is provided for an endpoint value, an existing web server listening connection will be used. In this case, the web server will typically be the virtual host that specifies the EjsStartup script. See the hosting web server documentation for specifics.
options: Object Set of options to configure the server. [default: expression]
options: Object null [default: expression]
Options
documentsDirectory containing web documents to serve. If unset and the HttpServer is hosted, the documents property will be defined by the web server.
homeBase directory for the server and the "ejsrc" configuration file. If unset and the HttpServer is hosted, the home property will be defined by the web server.
routesRoute table to use. Defaults to Router.Top.

listen(endpoint: String = null): Void
Description
Listen for client connections. This creates a HTTP server listening on a single socket endpoint. It can also be used to attach to an existing listening connection if embedded in a web server.

When hosted inside a web server, the web server will define the listening endpoints and ensure the EjsScript startup script is executed. Then, when listen() is called, the HttpServer object will be bound to the actual web server's listening connection. In this case, the endpoint argument is not required and is ignored.

HttpServer supports both sync and async modes of operation. In sync mode, after listen call is made, accept must be called to wait for and receive client connections. The accept call will create the Request object. In async mode, Request objects will be created automatically and passed to registered observers via "readable" events.
Parameters
endpoint: String The endpoint address on which to listen. An endoint may be a port number or a composite "IP:PORT" string. If only a port number is provided, the socket will listen on all interfaces on that port. The IP portion may also be "*"" to indicate all interfaces. If the server is hosted in a web server, an appropriate existing web server listening connection will be used. Otherwise, if not hosted, a server socket will be opened on the endpoint. If hosted and an endpoint is not provided, the server will listen on all appropriate web server connections. [default: null]
Events
IssuesA "accept" event when there is a new connection available.
Throws
ArgError: if the specified endpoint address is not valid or available for binding.
Example
server = new Http({home: ".", documents: "web"})
server.on("readable", function (event, request) {
    //  NOTE: "this" is set to the request
    server.serve(request)
})
server.listen("80")

off(name: Object, observer: Function): Void
Description
Remove an observer from the server.
Parameters
name: Object Event name previously used with observe. The name may be an array of events.
observer: Function Observer function previously used with observe.

on(name, observer: Function): HttpServer
Description
Add an observer for server events.
Parameters
name Name of the event to listen for. The name may be an array of events.
observer: Function Callback listening function. The function is called with the following signature: function on(event: String, ...args): Void.
Events
readableIssued when there is a new request available. This readable event will explicitly set the value of "this" to the request regardless of whether the function has a bound "this" value.
closeIssued when server is being closed.

passRequest(request: Request, worker: Worker)
Description
Pass a request into a worker VM. The onrequest callback receives the request. This routine clones stub Request and HttpServer objects into the worker VM.
Parameters
request: Request Request object.
worker: Worker Worker to handle the request H.

process(app: Function, request: Request, finalize: Boolean = true): Void
Description
Process a web request.
Parameters
request: Request Request object.
app: Function Web application function.
finalize: Boolean null [default: true]

pruneWorkers(): Void
Description
Prune idle worker threads. This will release cached worker interpreters and reduce memory footprint. After calling, the next request will be a little slower as it will need to recreate a worker interpreter. This is normally run every PrunePeriod. It may be also be called manually at any time. (.

run(): Void
Description
Run the application event loop to service requests. If the HttpServer is hosted in a web server, this call does nothing as the web server will service events and will return immediately.

secure(keyFile: Path, certFile: Path, protocols: Array = null, ciphers: Array = null): Void
Description
Define the Secure Sockets Layer (SSL) protocol credentials. This must be done before calling listen.
Parameters
keyFile: Path Path of the file containing the server's private key. This file contains the PEM encoded private key file for the server. Set to null if the private key is combined with the certificate file. If the private key is encrypted, you will be prompted at the console to enter the pass-phrase to decript the private key on system reboot. There is a delima here. If you use a crypted private key, the server will pause until you enter the pass-phrase which makes headless operation impossible. If you do not encrypt the private key, your private key is more vulnerable should the server be compromised. Which option you choose depends on whether headless operation is essential or not.
certFile: Path Path of the file containing the SSL certificate The certificate file contains the PEM encoded X.509 certificate for the server. The file may also contain the private key in which case you should set the key parameter to null. The path may be an absolute path or it may be relative to the ServerRoot.
protocols: Array Optional arary of SSL protocols to support. Select from: SSLv2, SSLv3, TLSv1, ALL. Each protocol can be prefixed by "+" or "-" to add or subtract from the prior set. For example: ["ALL", "-SSLv2"], or ["SSLv3", "TLSv1"] or "[ALL]". [default: null]
ciphers: Array Optional array of ciphers to use when negotiating the SSL connection. Not yet supported. [default: null]
Throws
ArgError: for invalid arguments

serve(request: Request, router: Router = expression): Void
Description
Serve a web request. Convenience function to route, load and start a web application. Called by web application start script.
Parameters
request: Request Request object.
router: Router Configured router instance. If omitted, a default Router will be created using the Router.Top routing table. [default: expression]

setLimits(limits: Object): Void
Description
Update the server resource limits. The supplied limit fields are updated. See the limits property for limit field details.
Parameters
limits: Object Object hash of limit fields and values.
See Also
limits

setPipeline(incoming: Array, outgoing: Array, connector: String): Void
Description
Define the stages of the Http processing pipeline. Data flows through the processing pipeline and is filtered or transmuted by filter stages. A communications connector is responsible for transmitting to the network.
Parameters
incoming: Array Array of stages for the incoming pipeline: default: ["chunk", "range", "upload"].
outgoing: Array Array of stages for the outgoing pipeline: default: ["auth", "range", "chunk"].
connector: String Network connector to use for I/O. Defaults to the network connector "net". Other values: "send". The "net" connector transparently upgrades to the "send" connector if transmitting static data and not using SSL, ranged or chunked transfers. `.

setWorkerImage(worker: Worker): Void
Description
Define a worker that will serve as the base for cloning workers to serve web requests.
Parameters
worker: Worker Configured worker.

trace(options: Object): Void
Description
Configure request tracing for the server. The default is to trace the first line of requests and responses at level 2 and to trace headers at level 3. The options argument contains optional properties. These contain an object hash which describes the following fields:.
Parameters
options: Object Set of trace options with properties for: The connection property specifies that new connections should be traced. The error property specifies that new connections should be traced. The info property specifies that new connections should be traced. The rxFirst property specifies that the first line of the request should be traced. The rxHeaders property specifies that the headers (including first line) of the request should be traced. The rxBody property specifies that the body content of the request should be traced. The txFirst property specifies that the first line of the response should be traced. The txHeaders property specifies that the headers (including first line) of the response should be traced. The txBody property specifies that the body content of the request should be traced. The complete property specifies that the body content of the request should be traced. The size property specifies a maximum body size in bytes that will be traced. Content beyond this limit will not be traced.
Example
trace({
    "rxHeaders": 3, "rxBody": 4, size: 1000000 }
})

verifyClients(caCertPath: Path, caCertFile: Path): Void
Description
Verify client certificates. This ensures that the clients must provide a client certificate for to verify the their identity. You can choose to use either the caCertPath or caCertFile argument. If both are provided caCertPath takes precedence.
Parameters
caCertPath: Path Defines the directory containing the certificates to use for client authentication. The path may be an absolute path or it may be relative to the ServerRoot. Set to null if you are using caCertFile.
caCertFile: Path Defines the location of the certificate file or bundle to use for client authentication. Use this if you have a single certificate or a bundle of certificates. Set to null if you are using caCertPath.