Skip to content

infinity.http2

Provides HTTP/2 server functionality with WebSocket support.

Module: infinity.http2

HTTP/2 Server Architecture Overview

The INFINITY.JS HTTP/2 server uses the same multi-threaded architecture as the HTTP server, with additional support for HTTP/2 multiplexing and WebSocket connections.

Architecture Highlights

HTTP/2 servers in INFINITY.JS benefit from: - Same Thread Pool Model: Uses maxConnections and poolSize parameters (see HTTP Architecture for details) - HTTP/2 Multiplexing: Multiple requests/responses on single TCP connection - WebSocket Support: Bidirectional communication with the scripts set in the onMessage and onBinary properties - Channels: WebSocket clients can subscribe to channels, the server can broadcast data to all clients of a channel - Connection Reuse: Reduced latency through persistent connections

graph TB
    subgraph "Main Program Thread"
        MainJS["main.js"]
        ServerObj["server = new infinity.http2.server()"]
        Listener["HTTP/2 Listener<br/>(TLS Required)"]
    end

    subgraph "Connection Queue"
        Queue["HTTP/2 Connections<br/>(Multiplexed Streams)"]
    end

    subgraph "Worker Thread Pool"
        Worker1["Worker Thread 1<br/>JavaScript Engine<br/>HTTP/2 Stream Handler"]
        Worker2["Worker Thread 2<br/>JavaScript Engine<br/>HTTP/2 Stream Handler"]
        WorkerN["Worker Thread N<br/>JavaScript Engine<br/>HTTP/2 Stream Handler"]
    end

    Client["HTTP/2 Client<br/>Multiple Streams"]

    MainJS --> ServerObj
    ServerObj --> Listener

    Client -->|"Single TCP + TLS<br/>Multiple Streams"| Listener
    Listener -->|"Stream 1, 3, 5..."| Queue

    Queue -.->|"Assign Stream"| Worker1
    Queue -.->|"Assign Stream"| Worker2
    Queue -.->|"Assign Stream"| WorkerN

    Worker1 -.->|"Response"| Client
    Worker2 -.->|"WebSocket Frame"| Client
    WorkerN -.->|"Response"| Client

    style MainJS fill:#4a90e2
    style Listener fill:#ab47bc
    style Queue fill:#ffa726
    style Worker1 fill:#7cb342
    style Worker2 fill:#7cb342
    style WorkerN fill:#7cb342
    style Client fill:#ef5350

HTTP/2-Specific Features

Stream Multiplexing: - Single TCP connection carries multiple request/response pairs (streams) - Each stream processed independently by worker threads - Eliminates head-of-line blocking from HTTP/1.1

WebSocket Support:

The onMessage and onBinary properties of the server contain the file names of scripts that are executed for each received WebSocket text or binary message. Inside these scripts, the infinity.http2.session namespace gives access to the message and the connection:

main.ts:

infinity.loadModule('infinity.http2');

let server = new infinity.http2.server(true);
server.onMessage = 'message.js';
server.start();

message.ts:

console.log('WebSocket message: ' + infinity.http2.session.message);
infinity.http2.session.writeString('Echo: ' + infinity.http2.session.message);

Connection Management: - Browsers only use HTTP/2 over TLS (HTTPS) - Up to 256 concurrent streams per connection - Worker threads assigned per stream, not per connection

Performance Benefits: - Reduced latency through multiplexing - Header compression (HPACK) reduces bandwidth - Binary protocol improves parsing efficiency

Request and response data: Scripts of custom handlers and service methods registered with httpEnvironment: true access the request and response data via infinity.http.request and infinity.http.response (there are no infinity.http2.request and infinity.http2.response namespaces).

For detailed thread pool architecture and configuration guidelines, see HTTP Server Architecture Overview.


Classes:
Namespaces:
Interfaces:

Classes

server

Allows for your instance of INFINITY.JS to act as an HTTP/2-server (also supporting HTTP/1.1 and WebSocket connections). Lets you receive requests and send data. Can register handlers for static files, single page applications, custom scripts, REST requests, the JSON-RPC protocol, API descriptions and a status report (JSON-RPC, REST and API handlers require the simultaneous usage of registerHandler() and registerService()). JSON-RPC and REST handlers can be combined in one service. The handlers work like the handlers of infinity.http.server; request and response data is available via infinity.http.request and infinity.http.response.

The server instance has no free() method; it is released when the object is garbage collected.

Example:

infinity.loadModule('infinity.http2');
let myServer = new infinity.http2.server(true, false, false, false, false, false, 443, 1024, 64, 104857600, 5.0);

myServer.registerHandler(infinity.http2.server.handler.status, '/status');
myServer.registerHandler(infinity.http2.server.handler.staticFile, '/', '../web/', 60.0, 256144);
myServer.registerHandler(infinity.http2.server.handler.jsonRpc, '/v1/jsonrpc');
myServer.registerService('system', 'system', 'system.js', [
  {name: 'shutdown'},
  {name: 'getVersion', result: 'string'}
]);

myServer.start();

while (!infinity.terminated) {
  infinity.event.processQueue();
  infinity.sleep(25);
}

myServer.stop();

system.ts:

namespace system {

    export function shutdown(): void {
      infinity.terminate();
    }

    export function getVersion(): string {
      return '1.0.0 build 1234';
    }
  }

Folder structure:

+ example
  + ts
    - main.ts
    - system.ts

Example POST-request against /v1/jsonrpc:

{"jsonrpc": "2.0", "method": "system.getVersion"}

Properties


onBinary

Type: string

The filename (relative to the folder of the main script) of the script that is executed for each binary WebSocket message. The property is evaluated by start(), which throws an error if the file does not exist. Default: '' (binary messages are ignored). Within that script, you can access the infinity.http2.session object, which will contain (among others) the following property:

  • fileName: the path to a temporary file containing the binary data sent by the client (the file is deleted after the script has finished)

onMessage

Type: string

The filename (relative to the folder of the main script) of the script that is executed for each text WebSocket message. The property is evaluated by start(), which throws an error if the file does not exist. Default: '' (text messages are ignored). Within that script, you can access the infinity.http2.session object, which will contain (among others) the following property:

  • message: the message text that has been sent by the client

Methods


constructor()

Lets you create an INFINITY.JS HTTP/2 server object instance. Takes the most important parameters for the server to function.

Signature:

constructor( ssl?: boolean, verifyCertificate?: boolean, allowCrossOrigin?: boolean, compress?: boolean, accessLog?: boolean, iocp?: boolean, port?: number, maxConnections?: number, poolSize?: number, maxContentLength?: number, slowRequestTime?: number, protocol?: infinity.http2.server.protocol, maxRateCounter?: number )

Parameters:

  • ssl: boolean, optional

    For using SSL connections. Default: false. If enabled, the server initially uses the certificate files infinity.crt, infinity.key and infinity.root.crt from the resources folder next to the folder of the INFINITY.JS executable. Use setCertificate() to set other certificate files.

  • verifyCertificate: boolean, optional

    Whether to verify SSL client certificates. Default: false.

  • allowCrossOrigin: boolean, optional

    For allowing cross-origin-requests (CORS headers). Default: false.

  • compress: boolean, optional

    For turning compression of responses on or off. Default: false.

  • accessLog: boolean, optional

    For turning on or off the logging of all requests to the console/log file. Default: false.

  • iocp: boolean, optional

    Specifies the usage of I/O completion ports (Windows) for socket handling. Default: false.

  • port: number, optional

    Specifies the port to listen on. Default: 443 if ssl is true, otherwise 80.

  • maxConnections: number, optional

    Specifies the maximum number of simultaneous connections. Default: 0 (unlimited).

  • poolSize: number, optional

    Specifies the number of worker threads to be held ready. Default: 0 (no thread pool).

  • maxContentLength: number, optional

    Specifies the maximum number of bytes (content-length header) that the server accepts in http requests. Default: 104857600 (100 MB).

  • slowRequestTime: number, optional

    Specifies how many seconds the processing of a request is allowed to take without being logged as "slow". Accepts decimals with . as well. Default: 0 (slow requests are not logged).

  • protocol: infinity.http2.server.protocol, optional

    Specifies the TLS version to be used. Default: all.

  • maxRateCounter: number, optional

    The maximum number of rate counters (one per handler and client IP address) tracked for rate limiting (see the limit, period and delay parameters of registerHandler()). If more addresses are tracked, all rate counters are reset. Default: 0 (unlimited).

Example:

infinity.loadModule('infinity.http2');
let myServer = new infinity.http2.server(true, false, false, false, false, false, 443, 1024, 64, 104857600, 5.0);

broadcast()

Sends data as JSON text message to all WebSocket clients that have subscribed to a specific channel. The channel name can be chosen arbitrarily and the data will be sent to all clients that are subscribed to the channel by this name.

Signature:

broadcast( data: any, channel?: string, exclude?: string, include?: string ): void

Parameters:

  • data: any

    Data to be sent (can be any object, number, string, etc.). The data is serialized to JSON, so a string is sent including quotes; use broadcastString() to send a string as it is.

  • channel: string, optional

    Channel name. If omitted, the data is sent to all clients.

  • exclude: string, optional

    Comma-separated list of client ids to exclude from the broadcast.

  • include: string, optional

    Comma-separated list of client ids to include from the broadcast (in addition to those subscribed to the given channel).

Example:

myServer.broadcast({event: 'update', id: 1}, 'news');

broadcastStream()

Sends data from a stream as binary message to all WebSocket clients that have subscribed to a specific channel. The channel name can be chosen arbitrarily and the data will be sent to all clients that are subscribed to the channel by this name.

Signature:

broadcastStream( stream: infinity.stream, channel?: string, exclude?: string, include?: string ): void

Parameters:

  • stream: infinity.stream

    A stream from which to read data and send it to the clients.

  • channel: string, optional

    Channel name. If omitted, the data is sent to all clients.

  • exclude: string, optional

    Comma-separated list of client ids to exclude from the broadcast.

  • include: string, optional

    Comma-separated list of client ids to include from the broadcast (in addition to those subscribed to the given channel).

Example:

myServer.broadcastStream(stream, 'news');

broadcastString()

Sends a string as text message to all WebSocket clients that have subscribed to a specific channel. The channel name can be chosen arbitrarily and the data will be sent to all clients that are subscribed to the channel by this name.

Signature:

broadcastString( message: string, channel?: string, exclude?: string, include?: string ): void

Parameters:

  • message: string

    Message to send to the clients.

  • channel: string, optional

    Channel name. If omitted, the message is sent to all clients.

  • exclude: string, optional

    Comma-separated list of client ids to exclude from the broadcast.

  • include: string, optional

    Comma-separated list of client ids to include from the broadcast (in addition to those subscribed to the given channel).

Example:

myServer.broadcastString('Hello subscribers', 'news');

registerHandler()

Registers a handler for client requests on the given path. The meaning of the parameters following path depends on the handler type:

  • jsonRpc, rest, api and status: registerHandler(handler, path, limit?, period?, delay?)
  • custom: registerHandler(handler, path, alias, limit?, period?, delay?)
  • staticFile and spa: registerHandler(handler, path, alias, expire?, maxCacheSize?, headers?, limit?, period?, delay?)

A handler registered for an already registered path replaces the previous handler. See infinity.http.server.registerHandler() for details.

Signatures:

registerHandler( handler: infinity.http2.server.handler, path: string, limit?: number, period?: number, delay?: number ): void
registerHandler( handler: infinity.http2.server.handler, path: string, alias: string, limit?: number, period?: number, delay?: number ): void
registerHandler( handler: infinity.http2.server.handler, path: string, alias: string, expire?: number, maxCacheSize?: number, headers?: infinity.http2.headerArray, limit?: number, period?: number, delay?: number ): void

Parameters:

  • handler: infinity.http2.server.handler

    The type of handler to register.

  • path: string

    The request path the handler is registered for.

  • alias: string

    Only for custom, staticFile and spa handlers. For custom handlers: the path of the script file (relative to the folder of the main script) that is executed for each request. For staticFile and spa handlers: the path of the folder (relative to the folder of the main script) containing the files to be served.

  • expire: number, optional

    Only for staticFile and spa handlers. The cache expiration time in whole seconds. After the specified period the file will have to be examined for changes at the next call. Default: 0 (files are not cached).

  • maxCacheSize: number, optional

    Only for staticFile and spa handlers. The cache threshold in bytes. Files with sizes exceeding the specified number will not be cached. Default: 0.

  • headers: infinity.http2.headerArray, optional

    Only for staticFile and spa handlers. Additional headers to be sent with every response of the handler.

  • limit: number, optional

    The maximum number of requests per client IP address that can be made to this handler in the defined period (rate limiting; every handler has its own counters). If the limit is exceeded, the request is answered with status code 429. Default: 0 (no rate limiting).

  • period: number, optional

    The rate limit time period in seconds.

  • delay: number, optional

    The number of seconds the server waits before sending the 429 response to a client that exceeded the rate limit.

Example:

myServer.registerHandler(infinity.http2.server.handler.status, '/status');
myServer.registerHandler(infinity.http2.server.handler.staticFile, '/', '../web/');
myServer.registerHandler(infinity.http2.server.handler.staticFile, '/', '../web/', 60, 256144);

registerService()

Registers a service, allowing requests for execution of custom defined methods. Supports parameter and result type validation using built-in types, validation constraints (e.g., number{1,}, string{3,32}), and custom types defined with registerTypes().

Signature:

registerService( name: string, namespace: string, path: string, methods: infinity.http2.methodArray ): void

Parameters:

  • name: string

    The name of the service.

  • namespace: string

    The namespace for the service.

  • path: string

    The path to the file with the custom defined methods.

  • methods: infinity.http2.methodArray

    An array of method definitions. Each method can specify: - name: Method name (required) - params: Array of parameter definitions with types and validation constraints - result: Declared return type (only used for the description generated by the api handler, return values are not validated) - rest: REST method mapping ('get', 'getList', 'post', 'put' or 'delete') - httpEnvironment: If true, provides access to infinity.http.request and infinity.http.response inside the method

Parameter Type Validation:

Supports the same validation syntax as infinity.http.server.registerService(): - number{min,max} - Numeric range validation - string{min,max} - String length validation - Custom types - Reference types defined with registerTypes()

Example:

myServer.registerHandler(infinity.http2.server.handler.jsonRpc, '/v1/jsonrpc');

// Basic service without validation
myServer.registerService('system', 'system', 'system.js', [
  {name: 'shutdown'},
  {name: 'getVersion', result: 'string'}
]);

// Service with validation constraints
myServer.registerService('users', 'users', 'users.js', [
  {
    name: 'login',
    params: ['username: string{3,32}', 'password: string{8,}'],
    result: 'object'
  },
  {
    name: 'get',
    params: ['id: number{1,}'],
    result: 'object'
  }
]);

For detailed validation syntax and examples, see: infinity.http.server.registerService()

system.ts:

namespace system {

  export function shutdown(): void {

    infinity.terminate();

  }

  export function getVersion(): string {

    return '1.0.0 build 1234';

  }

}

Folder structure:

+ example
  + ts
    - main.ts
    - system.ts

POST-request against /v1/jsonrpc:

{"jsonrpc": "2.0", "method": "system.getVersion"}

registerTypes()

Registers custom type definitions for request/response validation. This method works identically to infinity.http.server.registerTypes() and supports the same type system including enums, objects, and arrays with validation constraints.

Signature:

registerTypes( types: infinity.http.typesArray ): void

For complete documentation including validation syntax, examples, and type definition reference, see infinity.http.server.registerTypes().

Example:

infinity.loadModule('infinity.http2');

let http2 = new infinity.http2.server();

http2.registerTypes([
    {name: 'users.role', kind: 'enum', values: ['user = 1', 'admin = 2']},
    {name: 'users.user', kind: 'object', properties: [
        'id: number{0,}',
        'username: string{3,32}',
        'role?: users.role'
    ]}
]);

http2.registerService('users', 'users', 'users.js', [
    {name: 'add', params: ['user: users.user'], result: 'number'}
]);

unregisterTypes()

Unregisters a previously registered custom type definition. See infinity.http.server.unregisterTypes() for details.

Signature:

unregisterTypes( name: string ): void


setCertificate()

Sets the SSL certificate for the current server instance using the corresponding files provided in the function parameters. Throws an error if the server was created without SSL. Files that do not exist are ignored.

Signature:

setCertificate( certFile: string, keyFile: string, rootCertFile?: string, verify?: boolean ): void

Parameters:

  • certFile: string

    The path to the certificate file to be used.

  • keyFile: string

    The path to the key file to be used.

  • rootCertFile: string, optional

    The path to the root certificate file to be used.

  • verify: boolean, optional

    Whether to verify SSL client certificates. Default: false.

Example:

myServer.setCertificate('certFile.crt', 'keyFile.key', 'rootCertFile.crt', true);

start()

Starts the server instance with previously specified parameters. Evaluates the onMessage and onBinary properties.

Signature:

start(): void

Example:

myServer.start();

stop()

Shuts down the server instance.

Signature:

stop(): void

Example:

myServer.stop();

unregisterHandler()

Unregisters the specified registered handler, making the previously defined functionality unavailable.

Signature:

unregisterHandler( path: string ): void

Parameters:

  • path: string

    The request path for the client, which the handler has previously been registered for.

Example:

myServer.unregisterHandler('/');

unregisterService()

Unregisters the specified registered service, making the previously defined functionality unavailable.

Signature:

unregisterService( name: string ): void

Parameters:

  • name: string

    The name of the previously registered service.

Example:

myServer.unregisterService('system');

write()

Sends data as JSON text message to a specific WebSocket client connection. Returns whether the data could be sent.

Signature:

write( id: string, data: any ): boolean

Parameters:

  • id: string

    Id of the client connection (see infinity.http2.session.id).

  • data: any

    Data to be sent (can be any object, number, string, etc.). The data is serialized to JSON.

Return type: boolean

Example:

myServer.write(id, data);

writeStream()

Sends data from a stream as binary message to a specific WebSocket client connection. Returns whether the data could be sent.

Signature:

writeStream( id: string, stream: infinity.stream ): boolean

Parameters:

Return type: boolean

Example:

myServer.writeStream(id, stream);

writeString()

Sends a string as text message to a specific WebSocket client connection. Returns whether the message could be sent.

Signature:

writeString( id: string, message: string ): boolean

Parameters:

Return type: boolean

Example:

myServer.writeString(id, message);

Namespaces

infinity.http2.server

Enums:

Enums

infinity.http2.server.handler

Values:

  • custom: 0

    A custom handler: the script file specified in the third function parameter (alias) of registerHandler() is executed for each request. Inside the script, infinity.http.request and infinity.http.response are available.

  • staticFile: 1

    A handler for serving static file content from the folder specified in the alias parameter. For requests to a folder, the index.html file of the folder is served.

  • jsonRpc: 2

    A handler for requests according to the JSON-RPC protocol (calls methods of the registered services).

  • rest: 3

    A handler for REST-requests (calls methods of the registered services according to their rest mapping).

  • api: 4

    A handler that returns a JSON-WSP description of all registered services and methods (GET requests).

  • status: 5

    A handler for server-status requests, returning server and resource usage information as JSON.

  • spa: 6

    A handler for single page applications: like staticFile, but requests for files that do not exist are answered with the index.html (or index.htm) file of the alias folder.

Example:

infinity.loadModule('infinity.http2');
let handler = infinity.http2.server.handler.custom;

infinity.http2.server.protocol

Values:

  • all: 0

    No specific TLS version is set (default).

  • tls1_0: 1

    Specifies the usage of TLS 1.0.

  • tls1_1: 2

    Specifies the usage of TLS 1.1.

  • tls1_2: 3

    Specifies the usage of TLS 1.2.

  • tls1_3: 4

    Specifies the usage of TLS 1.3.

Example:

infinity.loadModule('infinity.http2');
let protocol = infinity.http2.server.protocol.tls1_2;

infinity.http2.session

The infinity.http2.session object is available in the scripts set in the onMessage and onBinary properties of the infinity.http2.server. It provides information about the WebSocket connection that sent the message and functions to send data back to it. Each message is processed in a new script runtime.


Functions

disconnect()

Disconnects the current WebSocket connection.

Signature:

disconnect(): void

Example:

infinity.loadModule('infinity.http2');
infinity.http2.session.disconnect();

subscribe()

Subscribes the current connection to a specific channel. The channel name can be chosen arbitrarily and the server can use the broadcast(), broadcastString() and broadcastStream() methods to send data to all connections that are subscribed to a specific channel.

Signature:

subscribe( channel: string ): void

Parameters:

  • channel: string

    Channel name.

Example:

infinity.loadModule('infinity.http2');
infinity.http2.session.subscribe(channel);

subscribed()

Checks whether the current connection has been subscribed to a specific channel.

Signature:

subscribed( channel: string ): boolean

Parameters:

  • channel: string

    Channel name.

Return type: boolean

Example:

infinity.loadModule('infinity.http2');
if ( infinity.http2.session.subscribed(channel) ) {}

unsubscribe()

Unsubscribes the current connection from a specific channel.

Signature:

unsubscribe( channel: string ): void

Parameters:

  • channel: string

    Channel name.

Example:

infinity.loadModule('infinity.http2');
infinity.http2.session.unsubscribe(channel);

write()

Sends data as JSON text message to the current connection.

Signature:

write( data: any ): void

Parameters:

  • data: any

    Data to be sent (can be any object, number, string, etc.). The data is serialized to JSON.

Example:

infinity.http2.session.write({status: 'ok'});

writeStream()

Sends data from a stream as binary message to the current connection.

Signature:

writeStream( stream: infinity.stream ): void

Parameters:

Example:

infinity.http2.session.writeStream(stream);

writeString()

Sends a string as text message to the current connection.

Signature:

writeString( message: string ): void

Parameters:

  • message: string

    Message to send.

Example:

infinity.http2.session.writeString('Echo: ' + infinity.http2.session.message);

Properties

fileName

Type: string

Only in the onBinary script: the path to a temporary file containing the binary data sent by the client. The file is deleted after the script has finished.


id

Type: string

The id of the WebSocket connection. It remains constant as long as the connection exists and can be used with the server methods write(), writeString() and writeStream() and the exclude/include parameters of the broadcast methods.


ip

Type: string

The IP address from which the client connected.


message

Type: string

Only in the onMessage script: the text message sent by the client.


port

Type: number

The port used by the connection with the client.


Interfaces

headerArray

Extends: Array<{name: string, value: string}>

An array of HTTP-header names and values.

Properties:

  • name

    Type: string. The field name.

  • value

    Type: string. The field value.


methodArray

Extends: Array<{name: string, params?: Array<string>, result?: any, rest?: string, httpEnvironment?: boolean}>

An array containing objects with data inside its properties.

Properties:

  • name

    Type: string. The name of the function.

  • params

    Type: Array<string>, optional. The function parameters in the format 'name: type' or 'name?: type' (optional parameter), see infinity.http.server.registerService().

  • result

    Type: any, optional. The declared return type of the function result (only used for the description of the api handler, not validated).

  • rest

    Type: string, optional. The REST verb the function is mapped to: 'get', 'getList', 'post', 'put' or 'delete'.

  • httpEnvironment

    Type: boolean, optional. If set to true, infinity.http.request and infinity.http.response are available inside the function.