Class

class Client

public class Client

Description: Sends HTTP requests and supports being closed at any time. Users can use a Client instance to send HTTP/1.1 or HTTP/2 requests.

Note:

If the Client document does not specify the supported version, the configuration is valid in both HTTP/1.1 and HTTP/2.

prop autoRedirect

public prop autoRedirect: Bool

Description: Specifies whether to enable automatic redirection for a client. By default, status code 304 indicates no redirection.

Type: Bool

prop connector

public prop connector: (SocketAddress) -> StreamingSocket

Description: A client calls this function to connect to the server.

Type: (SocketAddress) -> StreamingSocket

prop cookieJar

public prop cookieJar: ?CookieJar

Description: Stores all Cookie instances of a client. If this parameter is set to None, Cookie is disabled.

Type: ?CookieJar

prop enablePush

public prop enablePush: Bool

Description: Specifies whether the client-side HTTP/2 supports server push. The default value is true.

Type: Bool

prop headerTableSize

public prop headerTableSize: UInt32

Description: Obtains the initial value of the HTTP/2 Hpack dynamic table on a client. The default value is 4096.

Type: UInt32

prop httpProxy

public prop httpProxy: String

Description: Obtains the client-side HTTP proxy. By default, the value of the system environment variable http_proxy is used. The value is a string in the format of "http://host:port", for example, "http://192.168.1.1:80".

Type: String

prop httpsProxy

public prop httpsProxy: String

Description: Obtains the client-side HTTPS proxy. By default, the value of the system environment variable https_proxy is used. The value is a string in the format of "http://host:port", for example, "http://192.168.1.1:443".

Type: String

prop initialWindowSize

public prop initialWindowSize: UInt32

Description: Obtains the initial value of the HTTP/2 flow control window on a client. The default value is 65535. The value ranges from 0 to 2^31 – 1.

Type: UInt32

prop logger

public prop logger: Logger

Description: Obtains the client-side logger. The setting of logger.level takes effect immediately. The logger should be thread-safe.

Type: Logger

prop maxConcurrentStreams

public prop maxConcurrentStreams: UInt32

Description: Obtains the initial maximum number of concurrent HTTP/2 flows on a client. The default value is 2^31 – 1.

Type: UInt32

prop maxFrameSize

public prop maxFrameSize: UInt32

Description: Obtains the initial maximum frame size of HTTP/2 on a client. The default value is 16384. The value ranges from 2^14 to 2^24 – 1.

Type: UInt32

prop maxHeaderListSize

public prop maxHeaderListSize: UInt32

Description: Obtains the maximum header size of HTTP/2 supported by a client. The size refers to the sum of the maximum allowed lengths of all header fields in the response header, including the lengths of all field names and field values, and pseudo header overhead automatically added to each field. (Generally, each field has a 32-byte overhead, including the pseudo header information added by the HTTP/2 protocol to the header field.) By default, this maximum length is set to UInt32.Max.

Type: UInt32

prop poolSize

public prop poolSize: Int64

Description: Configures the size of the connection pool used by an HTTP/1.1 client, which also means the maximum number of concurrent connections to the same host (host:port).

Type: Int64

prop readTimeout

public prop readTimeout: Duration

Description: Obtains the timeout for reading the entire response set on a client. The default value is 15s.

Type: Duration

prop writeTimeout

public prop writeTimeout: Duration

Description: Obtains the timeout for write requests set on a client. The default value is 15s.

Type: Duration

func close()

public func close(): Unit

Description: Closes all connections established by a client. After this function is called, requests cannot be sent.

func connect(String, HttpHeaders, Protocol)

public func connect(url: String, header!: HttpHeaders = HttpHeaders(), version!: Protocol = HTTP1_1): (HttpResponse, ?StreamingSocket)

Description: Sends a CONNECT request to establish a tunnel with the server and returns the connection successfully established. Such connection is closed by the user. If the server returns 2xx, the connection is established successfully. Otherwise, the connection fails. (Automatic redirection is not supported. The connection fails if the server returns 3xx.)

Parameters:

  • url: String: URL of the request
  • header!: HttpHeaders: request header, which is empty by default
  • version!: Protocol: protocol (HTTP1_1 by default) of the request

Returns:

Throws:

  • UrlSyntaxException: When the URL does not comply with the URL parsing specifications, this exception is thrown.
  • IllegalArgumentException: When the encoded character does not comply with the UTF-8 byte sequence rule, this exception is thrown.
  • Other exceptions are the same as those in func send.

func delete(String)

public func delete(url: String): HttpResponse

Description: Specifies a shortcut request function whose request method is DELETE.

Parameters:

  • url: String: URL of the request

Returns:

Throws:

  • UrlSyntaxException: When the URL does not comply with the URL parsing specifications, this exception is thrown.
  • IllegalArgumentException: When the encoded character does not comply with the UTF-8 byte sequence rule, this exception is thrown.
  • Other exceptions are the same as those in func send.

func get(String)

public func get(url: String): HttpResponse

Description: Specifies a shortcut request function whose request method is GET.

Parameters:

  • url: String: URL of the request

Returns:

Throws:

  • UrlSyntaxException: When the URL does not comply with the URL parsing specifications, this exception is thrown.
  • IllegalArgumentException: When the encoded character does not comply with the UTF-8 byte sequence rule, this exception is thrown.
  • Other exceptions are the same as those in func send.

func getTlsConfig()

public func getTlsConfig(): ?TlsClientConfig

Description: Obtains the TLS layer configuration set by a client.

Returns:

  • ?TlsClientConfig: TLS layer configuration set by the client. If it is not set, None is returned.

func head(String)

public func head(url: String): HttpResponse

Description: Specifies a shortcut request function whose request method is HEAD.

Parameters:

  • url: String: URL of the request

Returns:

Throws:

  • UrlSyntaxException: When the URL does not comply with the URL parsing specifications, this exception is thrown.
  • IllegalArgumentException: When the encoded character does not comply with the UTF-8 byte sequence rule, this exception is thrown.
  • Other exceptions are the same as those in func send.

func options(String)

public func options(url: String): HttpResponse

Description: Specifies a shortcut request function whose request method is OPTIONS.

Parameters:

  • url: String: URL of the request

Returns:

Throws:

  • UrlSyntaxException: When the URL does not comply with the URL parsing specifications, this exception is thrown.
  • IllegalArgumentException: When the encoded character does not comply with the UTF-8 byte sequence rule, this exception is thrown.
  • Other exceptions are the same as those in func send.

func post(String, Array<UInt8>)

public func post(url: String, body: Array<UInt8>): HttpResponse

Description: Specifies a shortcut request function whose request method is POST.

Parameters:

Returns:

Throws:

  • UrlSyntaxException: When the URL does not comply with the URL parsing specifications, this exception is thrown.
  • IllegalArgumentException: When the encoded character does not comply with the UTF-8 byte sequence rule, this exception is thrown.
  • Other exceptions are the same as those in func send.

func post(String, InputStream)

public func post(url: String, body: InputStream): HttpResponse

Description: Specifies a shortcut request function whose request method is POST.

Parameters:

Returns:

Throws:

  • UrlSyntaxException: When the URL does not comply with the URL parsing specifications, this exception is thrown.
  • IllegalArgumentException: When the encoded character does not comply with the UTF-8 byte sequence rule, this exception is thrown.
  • Other exceptions are the same as those in func send.

func post(String, String)

public func post(url: String, body: String): HttpResponse

Description: Specifies a shortcut request function whose request method is POST.

Parameters:

  • url: String: URL of the request
  • body: String: request body

Returns:

Throws:

  • UrlSyntaxException: When the URL does not comply with the URL parsing specifications, this exception is thrown.
  • IllegalArgumentException: When the encoded character does not comply with the UTF-8 byte sequence rule, this exception is thrown.
  • Other exceptions are the same as those in func send.

func put(String, Array<UInt8>)

public func put(url: String, body: Array<UInt8>): HttpResponse

Description: Specifies a shortcut request function whose request method is PUT.

Parameters:

Returns:

Throws:

  • UrlSyntaxException: When the URL does not comply with the URL parsing specifications, this exception is thrown.
  • IllegalArgumentException: When the encoded character does not comply with the UTF-8 byte sequence rule, this exception is thrown.
  • Other exceptions are the same as those in func send.

func put(String, InputStream)

public func put(url: String, body: InputStream): HttpResponse

Description: Specifies a shortcut request function whose request method is PUT.

Parameters:

Returns:

Throws:

  • UrlSyntaxException: When the URL does not comply with the URL parsing specifications, this exception is thrown.
  • IllegalArgumentException: When the encoded character does not comply with the UTF-8 byte sequence rule, this exception is thrown.
  • Other exceptions are the same as those in func send.

func put(String, String)

public func put(url: String, body: String): HttpResponse

Description: Specifies a shortcut request function whose request method is PUT.

Parameters:

  • url: String: URL of the request
  • body: String: request body

Returns:

Throws:

  • UrlSyntaxException: When the URL does not comply with the URL parsing specifications, this exception is thrown.
  • IllegalArgumentException: When the encoded character does not comply with the UTF-8 byte sequence rule, this exception is thrown.
  • Other exceptions are the same as those in func send.

func send(HttpRequest)

public func send(req: HttpRequest): HttpResponse

Description: Specifies a common request function, which sends HttpRequest to the server in URL and receives HttpResponse.

Note:

  • For HTTP/1.1, if the request to be sent contains a body, ensure that either Content-Length or Transfer-Encoding: chunked is set. If the body is sent in chunked mode, the maximum size of each chunk is 8,192 bytes. If the body sent by the user is a self-implemented InputStream class, the user must ensure that either Content-Length or Transfer-Encoding: chunked is set. If the user uses a default body to send a request and both Content-Length and Transfer-Encoding: chunked are missing, a Content-Length header whose value is body.size is added by default.
  • If Content-Length is set, ensure that its value is correct. If the body to be sent is greater than or equal to the value of Content-Length, the data whose length is the value of Content-Length is sent. If the body to be sent is a default body and is less than the value of Content-Length, HttpException is thrown. If the body is a self-implemented InputStream class, the result is unpredictable (read request timeout on the server or response receiving timeout on the client may occur).
  • The upgrade function is sent through the upgradeFromClient interface of WebSocket or the upgrade interface of Client. An exception will be thrown when another function of the client is called to send the upgrade request.
  • According to the protocol, a TRACE request cannot carry content. Therefore, an exception is thrown when the user sends a TRACE request with a body.
  • By default, the number of HTTP/1.1 connections to the same server cannot exceed 10. The response body needs to be read by calling the body.read(buf: Array<Byte>) function. A connection can be reused by client objects only after the body is read. Otherwise, a new connection is still created even for the same server. If the number of connections exceeds the upper limit during connection creation, HttpException is thrown.
  • The body.read function returns 0 after reading the body. If the connection is interrupted during the read, ConnectionException is thrown.
  • If a 101 response code is received for the HTTP/1.1 upgrade request, the protocol is switched and the connection is not managed by the client.
  • The notes for the following shortcut request functions are the same as those for the send function.

Parameters:

Returns:

  • HttpResponse: response returned by the server for processing the request

Throws:

func upgrade(HttpRequest)

public func upgrade(req: HttpRequest): (HttpResponse, ?StreamingSocket)

Description: Sends a request and upgrades the protocol. The user sets the request header and the upgraded connection is returned (if the upgrade is successful). Such connection is closed by the user.

Note:

  • If the server returns 101, the upgrade is successful and StreamingSocket is obtained.
  • Mandatory request headers:
    • Upgrade: protocol-name ["/" protocol-version]
    • Connection: Upgrade (automatically added when the request header contains the Upgrade field)
  • HTTP/1.0 or HTTP/2 is not supported.
  • HttpRequest of the HTTP/1.1 CONNECT method is not supported.

Parameters:

Returns:

Throws:

  • HttpException -
    • The request packet or response packet does not comply with the protocol.
    • The request packet does not contain the Upgrade header.
    • A CONNECT request is sent.
    • A TRACE request with a body is sent.
  • SocketException, ConnectionException: Socket connection is abnormal or closed.
  • SocketTimeoutException: Socket connection times out.
  • TlsException: TLS connection fails to be established or the communication is abnormal.

class ClientBuilder

public class ClientBuilder {
    public init()
}

Description: Constructs a Client instance. Client does not have any public constructor. Users can obtain Client instances only by using ClientBuilder. If the ClientBuilder document does not specify the supported version, the configuration is valid in both HTTP/1.1 and HTTP/2.

init()

public init()

Description: Creates a new ClientBuilder instance.

func autoRedirect(Bool)

public func autoRedirect(auto: Bool): ClientBuilder

Description: Configures whether to enable automatic redirection for a client. A redirection requests resources in the Location header. According to the protocol, Location can contain only one URI reference: Location = URI-reference. For details, see RFC 9110 10.2.2.. By default, status code 304 indicates no redirection.

Parameters:

  • auto: Bool: The default value is true, indicating that automatic redirection is enabled.

Returns:

func build()

public func build(): Client

Description: Constructs a Client instance.

Returns:

Throws:

func connector((SocketAddress)->StreamingSocket)

public func connector(connector: (SocketAddress)->StreamingSocket): ClientBuilder

Description: A client calls this function to connect to the server.

Parameters:

Returns:

func cookieJar(?CookieJar)

public func cookieJar(cookieJar: ?CookieJar): ClientBuilder

Description: Stores all Cookie instances of a client.

Parameters:

Returns:

func enablePush(Bool)

public func enablePush(enable: Bool): ClientBuilder

Description: Configures whether the client-side HTTP/2 supports server push.

Parameters:

  • enable: Bool: The default value is true.

Returns:

func headerTableSize(UInt32)

public func headerTableSize(size: UInt32): ClientBuilder

Description: Configures the initial value of the HTTP/2 Hpack dynamic table on a client.

Parameters:

  • size: UInt32: The default value is 4096.

Returns:

func httpProxy(String)

public func httpProxy(addr: String): ClientBuilder

Description: Sets the HTTP proxy of a client. By default, the value of the system environment variable http_proxy is used.

Parameters:

  • addr: String: The format is "http://host:port", for example, "http://192.168.1.1:80".

Returns:

func httpsProxy(String)

public func httpsProxy(addr: String): ClientBuilder

Description: Sets the HTTPS proxy of a client. By default, the value of the system environment variable https_proxy is used.

Parameters:

  • addr: String: The format is "http://host:port", for example, "http://192.168.1.1:443".

Returns:

func initialWindowSize(UInt32)

public func initialWindowSize(size: UInt32): ClientBuilder

Description: Configures the initial value of the HTTP/2 flow control window on a client.

Parameters:

  • size: UInt32: The default value is 65535. The value ranges from 0 to 2^31 – 1.

Returns:

func logger(Logger)

public func logger(logger: Logger): ClientBuilder

Description: Sets the client-side logger. The default logger level is INFO. The logger content is written to Console.stdout.

Parameters:

  • logger: Logger: The logger must be thread-safe. By default, the built-in thread-safe logger is used.

Returns:

func maxConcurrentStreams(UInt32)

public func maxConcurrentStreams(size: UInt32): ClientBuilder

Description: Configures the initial maximum number of concurrent HTTP/2 flows on a client.

Parameters:

  • size: UInt32: The default value is 2^31 – 1.

Returns:

func maxFrameSize(UInt32)

public func maxFrameSize(size: UInt32): ClientBuilder

Description: Configures the initial maximum frame size of HTTP/2 on a client.

Parameters:

  • size: UInt32: The default value is 16384. The value ranges from 2^14 to 2^24 – 1.

Returns:

func maxHeaderListSize(UInt32)

public func maxHeaderListSize(size: UInt32): ClientBuilder

Description: Obtains the maximum header size of HTTP/2 supported by a client. The size refers to the sum of the maximum allowed lengths of all header fields in the response header, including the lengths of all field names and field values, and pseudo header overhead automatically added to each field. (Generally, each field has a 32-byte overhead, including the pseudo header information added by the HTTP/2 protocol to the header field.) By default, this maximum length is set to UInt32.Max.

Parameters:

  • size: UInt32: maximum length of the HTTP/2 response headers received by the client

Returns:

func noProxy()

public func noProxy(): ClientBuilder

Description: After this function is called, the client does not use any proxy.

Returns:

func poolSize(Int64)

public func poolSize(size: Int64): ClientBuilder

Description: Configures the size of the connection pool used by an HTTP/1.1 client, which also means the maximum number of concurrent connections to the same host (host:port).

Parameters:

  • size: Int64: The default value is 10. The value of poolSize must be greater than 0.

Returns:

Throws:

  • HttpException: If the input parameter is less than or equal to 0, this exception is thrown.

func readTimeout(Duration)

public func readTimeout(timeout: Duration): ClientBuilder

Description: Sets the maximum duration for a client to read a response.

Parameters:

Returns:

func tlsConfig(TlsClientConfig)

public func tlsConfig(config: TlsClientConfig): ClientBuilder

Description: Sets the TLS layer configuration which is not set by default.

Parameters:

  • config: TlsClientConfig: configuration information required for supporting the TLS client

Returns:

func writeTimeout(Duration)

public func writeTimeout(timeout: Duration): ClientBuilder

Description: Sets the maximum duration for a client to send a request.

Parameters:

Returns:

public class Cookie {
    public init(name: String, value: String, expires!: ?DateTime = None, maxAge!: ?Int64 = None,
        domain!: String = "", path!: String = "", secure!: Bool = false, httpOnly!: Bool = false)
}

Description: HTTP is stateless. To obtain the client status and provide personalized services, the server can use Cookie to maintain a stateful session.

Note:

  • When the user accesses a site for the first time, the server sends the name/value pair and attribute-value to the user proxy through the Set-Cookie header. The user proxy can then add the name/value to the Cookie header in subsequent requests to the site.
  • The Cookie class provides functions for constructing Cookie objects, converting Cookie objects to Set-Cookie header values, and obtaining the attribute values of Cookie objects.
  • For details about the requirements and functions of attributes of Cookie, see RFC 6265.
  • In the following content, names such as cookie-name, cookie-value, and expires-av are subject to the terms in RFC 6265. See the protocol for details.

prop cookieName

public prop cookieName: String

Description: Obtains the cookie-name value of a Cookie object.

Type: String

prop cookieValue

public prop cookieValue: String

Description: Obtains the cookie-value value of a Cookie object.

Type: String

prop domain

public prop domain: String

Description: Obtains the domain-av value of a Cookie object.

Type: String

prop expires

public prop expires: ?DateTime

Description: Obtains the expires-av value of a Cookie object.

Type: ?DateTime

prop httpOnly

public prop httpOnly: Bool

Description: Obtains the httpOnly-av value of a Cookie object.

Type: Bool

prop maxAge

public prop maxAge: ?Int64

Description: Obtains the max-age-av value of a Cookie object.

Type: ?Int64

prop others

public prop others: ArrayList<String>

Description: Obtains the attributes that are not parsed.

Type: ArrayList<String>

prop path

public prop path: String

Description: Obtains the path-av value of a Cookie object.

Type: String

prop secure

public prop secure: Bool

Description: Obtains the secure-av value of a Cookie object.

Type: Bool

init(String, String, ?DateTime, ?Int64, String, String, Bool, Bool)

public init(name: String, value: String, expires!: ?DateTime = None, maxAge!: ?Int64 = None,
    domain!: String = "", path!: String = "", secure!: Bool = false, httpOnly!: Bool = false)

Description: Provides the public constructor for Cookie objects. Note: This constructor checks whether the input attributes meet the protocol requirements. If the requirement is not met, IllegalArgumentException is thrown. For details, see RFC 6265 4.1.1..

Note:

For all attributes of Cookie, only cookie-name and cookie-value are mandatory. The name and value parameters are mandatory, but the value parameter can be an empty string.

Parameters:

  • name: String: cookie-name attribute

    name         = token 
    token        = 1*tchar
    tchar        = "!" / "#" / "$" / "%" / "&" / "'" / "*"
                   / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
                   / DIGIT / ALPHA
    
  • value: String: cookie-value attribute

    value        = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
    cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
                ; US-ASCII characters excluding CTLs,
                ; whitespace DQUOTE, comma, semicolon,
                ; and backslash
    
  • expires!: ?DateTime: Set the expiration time of Cookie. The default value is None. The time must be later than year 1601.

  • maxAge!: ?Int64: maximum lifetime of Cookie. The default value is None. If the Cookie has both the expires and maxAge attributes, the Cookie is maintained only until the end of the session. (It is maintained until the Client is closed. A Cookie with expiration time set is no longer maintained after the Client is closed.)

    max-age-av     = "Max-Age=" non-zero-digit *DIGIT
    non-zero-digit = %x31-39
                    ; digits 1 through 9
    DIGIT          = %x30-39
                    ; digits 0 through 9
    
  • domain!: String: empty string by default, indicating that the client receives the Cookie and sends the Cookie only to the origin server. If a valid domain is set, the client receives the Cookie and sends the Cookie only to all subdomains of the domain (only when other attribute requirements are met).

    domain          = <subdomain> | " "
    <subdomain>   ::= <label> | <subdomain> "." <label>
    <label>       ::= <letter> [ [ <ldh-str> ] <let-dig> ]
    <ldh-str>     ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
    <let-dig-hyp> ::= <let-dig> | "-"
    <let-dig>     ::= <letter> | <digit>
    <letter>      ::= any one of the 52 alphabetic characters A through Z in upper case and a through z in lower case
    <digit>       ::= any one of the ten digits 0 through 9
    RFC 1035 2.3.1.
    RFC 1123 2.1. eliminates the restriction that the first character of a label must be a letter.
    Therefore, the requirements for a domain are as follows:
    1. It consists of several labels, with the total length less than or equal to 255 characters.
    2. Labels are separated by periods (.). Each label contains a maximum of 63 characters.
    3. A label must start and end with a digit or letter, and the middle character of a label must be a digit, letter, or hyphen (-).
    
  • path!: String: empty string by default. The client calculates the default path attribute based on the URL. For details, see RFC 6265 5.1.4. The client receives the Cookie and sends the Cookie only to all subdirectories of the path (only when other attribute requirements are met).

    path            = <any RUNE except CTLs or ";">
    RUNE            = <any [USASCII] character>
    CTLs            = <controls>
    
  • secure!: Bool: The default value is false. If the value is true, the Cookie is sent only in requests under secure protocols.

  • httpOnly!: Bool: The default value is false. If the value is true, the Cookie is sent only in requests under HTTP protocols.

Throws:

func toSetCookieString()

public func toSetCookieString(): String

Description: Provides a function for converting Cookie to a string so that the server can set the Set-Cookie header.

Note:

  • The attributes (including name and value) of the Cookie are checked when the object is created. Therefore, the toSetCookieString() function does not throw exceptions.
  • The mandatory attribute of Cookie is cookie-pair, that is, cookie-name = cookie-value. cookie-value can be an empty string. The toSetCookieString() function writes only the configured attribute into the string, which means only "cookie-name=" is mandatory and whether other attributes exist depends on whether they are set.

Returns:

  • String: string object used to set the Set-Cookie header

class FileHandler

public class FileHandler <: HttpRequestHandler {
    public init(path: String, handlerType!: FileHandlerType = DownLoad, bufferSize!: Int64 = 64 * 1024)
}

Description: Handles file download or upload.

File download:

  • The path of the file to be downloaded needs to be input for constructing the FileHandler. Currently, one FileHandler can handle the download of only one file.
  • Only the GET request method can be used to download files. If other request methods are used, status code 400 is returned.
  • If the file does not exist, status code 404 is returned.

File upload:

  • An existing directory path needs to be input for constructing the FileHandler. The files uploaded to the server are stored in this directory.
  • Only the POST request method can be used to upload files. If other request methods are used, status code 400 is returned.
  • The HTTP packet for data upload must be in multipart/form-data format, and the value of the Content-Type header field must be multipart/form-data; boundary=----XXXXX.
  • Names of the files uploaded are stored in the form-data packet. The packet data format is Content-Disposition: form-data; name="xxx"; filename="xxxx", and the file name is the value of the filename field.
  • Currently, form-data must contain the filename field.
  • If the request packet is incorrect, status code 400 is returned.
  • If another exception is thrown, for example, a file processing exception is thrown, status code 500 is returned.

Parent Type:

init(String, FileHandlerType, Int64)

public init(path: String, handlerType!: FileHandlerType = DownLoad, bufferSize!: Int64 = 64 * 1024)

Description: Specifies the constructor of FileHandler.

Parameters:

  • path: String: file or directory path string input for constructing the FileHandler. Only an existing directory path can be input in the upload mode. If the path contains "../", the expected path to be input must be a standardized absolute path.
  • handlerType!: FileHandlerType: working mode of the current FileHandler for constructing the FileHandler. The default mode is the download mode.
  • bufferSize!: Int64: size of the buffer internally read from or written to network. The default size is 64 x 1024 (64 KB). If the value is less than 4096, 4096 is used.

Throws:

  • HttpException: If the path does not exist, this exception is thrown.

func handle(HttpContext)

public func handle(ctx: HttpContext): Unit

Description: Processes response data based on requests.

Parameters:

class FuncHandler

public class FuncHandler <: HttpRequestHandler {
    public FuncHandler((HttpContext) -> Unit)
}

Description: Specifies an HttpRequestHandler interface wrapper class, which wraps a single function into HttpRequestHandler.

Parent Type:

FuncHandler((HttpContext) -> Unit)

public FuncHandler(let handler: (HttpContext) -> Unit)

Description: Specifies the constructor of FuncHandler.

Parameters:

func handle(HttpContext)

public func handle(ctx: HttpContext): Unit

Description: Processes an HTTP request.

Parameters:

class HttpContext

public class HttpContext

Description: Specifies the HTTP request context used as the parameter of the HttpRequestHandler.handle function on the server.

prop clientCertificate

public prop clientCertificate: ?Array<X509Certificate>

Description: Obtains the HTTP certificate of a client.

Type: ?Array<X509Certificate>

prop request

public prop request: HttpRequest

Description: Obtains an HTTP request.

Type: HttpRequest

prop responseBuilder

public prop responseBuilder: HttpResponseBuilder

Description: Obtains the HTTP response builder.

Type: HttpResponseBuilder

class HttpHeaders

public class HttpHeaders <: Iterable<(String, Collection<String>)> {
    public init()
}

Description: This class indicates the header and trailer in an HTTP packet and defines related add, delete, modify, and query operations.

Note:

  • The header and trailer are key-value mapping sets, consisting of several field-lines. Each field-line contains a key (field-name) and several values (field-value).
  • The field-name consists of token characters, which are case-insensitive. In this class, the characters are stored in lowercase format.
  • The field-value consists of vchar (visible US-ASCII characters), SP, and HTAB. It cannot be empty or contain spaces at the beginning or end.
  • For details, see rfc 9110.

Parent Type:

Example:

Example-Field: Foo, Bar
key: Example-Field, value: Foo, Bar
field-name = token
token = 1*tchar
tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
/ "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
/ DIGIT / ALPHA
; any VCHAR, except delimiters

init()

public init()

Description: Creates an HttpHeaders instance.

func add(String, String)

public func add(name: String, value: String): Unit

Description: Adds a specified key-value pair. If the name field already exists, its value is added to the corresponding value list. If the name field does not exist, the name field and its value are added.

Parameters:

Throws:

  • HttpException: If the input name or value contains invalid elements, this exception is thrown.

func del(String)

public func del(name: String): Unit

Description: Deletes the key-value pair of a specified name.

Parameters:

  • name: String: name of the field deleted

func get(String)

public func get(name: String): Collection<String>

Description: Obtains the value corresponding to a specified name.

Parameters:

  • name: String: field name, which is case-insensitive

Returns:

  • Collection<String>: value collection corresponding to the name. If the specified name does not exist, an empty collection is returned.

func getFirst(String)

public func getFirst(name: String): ?String

Description: Obtains the first value corresponding to a specified name.

Parameters:

  • name: String: field name, which is case-insensitive

Returns:

  • ?String: first value corresponding to the name. If the specified name does not exist, None is returned.

func isEmpty()

public func isEmpty(): Bool

Description: Checks whether the current instance is empty, that is, checks there is no key-value pair.

Returns:

  • Bool: If the current instance is empty, true is returned. Otherwise, false is returned.

func iterator()

public func iterator(): Iterator<(String, Collection<String>)>

Description: Obtains an iterator that can be used to traverse all key-value pairs.

Returns:

func set(String, String)

public func set(name: String, value: String): Unit

Description: Sets a specified key-value pair. If the name already exists, the input value overwrites the previous one.

Parameters:

Throws:

  • HttpException: If the input name or value contains invalid elements, this exception is thrown.

class HttpRequest

public class HttpRequest <: ToString

Description: This class is an HTTP request class.

When sending a request, a client needs to construct an HttpRequest instance, encode the instance into a byte packet, and send the packet.

When processing a request, the server parses the received request into an HttpRequest instance and sends it to the handler function.

Parent Type:

prop body

public prop body: InputStream

Description: Obtains a body.

Note:

  • The body does not support concurrent read.
  • By default, the read function of the InputStream implementation class does not support multiple reads.

Type: InputStream

prop bodySize

public prop bodySize: Option<Int64>

Description: Obtains the length of a request body.

  • If the body is not set, bodySize is Some(0).
  • If the body length is known, that is, the body is input through Array<UInt8> or String, or the input InputStream has a definite length (length >= 0), bodySize is Some(Int64).
  • If the body length is unknown, that is, the body is input through a user-defined InputStream instance and the InputStream instance does not have a definite length (length < 0), bodySize is set to None.

Type: Option<Int64>

prop close

public prop close: Bool

Description: Specifies whether the request header contains Connection: close.

  • For the server, if close is set to true, the connection is closed after the request is fulfilled.
  • For a client, if close is set to true, the client needs to close the connection if the server does not close the connection after receiving the response.

Type: Bool

prop form

public prop form: Form

Description: Obtains the form information in the request.

  • If the POST, PUT, or PATCH method is used and content-type contains application/x-www-form-urlencoded, the request body is obtained and parsed in form format.
  • If neither the POST, PUT, nor PATCH method is used, the query field in the request URL is obtained.

Note:

  • If this API is used to read the body and the body has been consumed, the body cannot be read through body.read.
  • If the form is not in the Form format, the UrlSyntaxException exception is thrown.

Type: Form

prop headers

public prop headers: HttpHeaders

Description: Obtains headers. For details about headers, see the HttpHeaders class. After headers are obtained, the HttpHeaders instance function can be called to modify headers of the request.

Type: HttpHeaders

prop method

public prop method: String

Description: Obtains a method, for example, "GET" or "POST". The method of a request instance cannot be modified.

Type: String

prop readTimeout

public prop readTimeout: ?Duration

Description: Specifies the request-level read timeout of the request. None indicates that the read timeout is not set. Some(Duration) indicates that the read timeout is set.

Type: ?Duration

prop remoteAddr

public prop remoteAddr: String

Description: Obtains the peer address (client address) by the server. The format is ip:port, which cannot be set by users. If a user-defined request object calls this attribute, "" is returned. If the server handler calls this attribute, the client address is returned.

Type: String

prop trailers

public prop trailers: HttpHeaders

Description: Obtains trailers. For details about trailers, see the HttpHeaders class. After trailers are obtained, the HttpHeaders instance function can be called to modify trailers of the request.

Type: HttpHeaders

prop url

public prop url: URL

Description: Obtains the URL accessed by a client.

Type: URL

prop version

public prop version: Protocol

Description: Obtains the HTTP version, such as HTTP1_1 and HTTP2_0. The version of a request instance cannot be changed.

Type: Protocol

prop writeTimeout

public prop writeTimeout: ?Duration

Description: Specifies the request-level write timeout of the request. None indicates that the write timeout is not set. Some(Duration) indicates that the write timeout is set.

Type: ?Duration

func toString()

public override func toString(): String

Description: Converts a request to a string, including start line, headers, body size, and trailers. For example, "GET /path HTTP/1.1\r\nhost: www.example.com\r\n\r\nbody size: 5\r\nbar: foo\r\n".

Returns:

  • String: string representation of the request

class HttpRequestBuilder

public class HttpRequestBuilder {
    public init()
}

Description: The HttpRequestBuilder class is used to construct HttpRequest instances.

init()

public init()

Description: Constructs a new HttpRequestBuilder.

init(HttpRequest)

public init(request: HttpRequest)

Description: Constructs an HttpRequestBuilder having the request attribute through a request. Since the body is an InputStream, operations on the original request body affect the HttpRequest body copy. The headers and trailers of HttpRequestBuilder are deep copies of the input parameter request. Other elements are shallow copies of the input parameter request because they are immutable objects.

Parameters:

func addHeaders(HttpHeaders)

public func addHeaders(headers: HttpHeaders): HttpRequestBuilder

Description: Adds the key-value pairs in HttpHeaders to the request header.

Parameters:

Returns:

func addTrailers(HttpHeaders)

public func addTrailers(trailers: HttpHeaders): HttpRequestBuilder

Description: Adds the key-value pairs in HttpHeaders to the request trailer.

Parameters:

Returns:

func body(Array<UInt8>)

public func body(body: Array<UInt8>): HttpRequestBuilder

Description: Sets the request body. If the body has been set, calling this function replaces the original body.

Parameters:

  • body: Array<UInt8>: request body in byte array format

Returns:

func body(InputStream)

public func body(body: InputStream): HttpRequestBuilder

Description: Sets the request body. If the body has been set, calling this function replaces the original body.

Parameters:

Returns:

func body(String)

public func body(body: String): HttpRequestBuilder

Description: Sets the request body. If it has been set, calling this function replaces the original body. If this function is called to set the request body, the body is represented by the built-in InputStream implementation class, and its size is known.

Parameters:

  • body: String: request body in string format

Returns:

func build()

public func build(): HttpRequest

Description: Generates an HttpRequest instance based on the HttpRequestBuilder instance.

Returns:

func connect()

public func connect(): HttpRequestBuilder

Description: Constructs a shortcut request function whose request method is "CONNECT".

Returns:

func delete()

public func delete(): HttpRequestBuilder

Description: Constructs a shortcut request function whose request method is "DELETE".

Returns:

func get()

public func get(): HttpRequestBuilder

Description: Constructs a shortcut request function whose request method is "GET".

Returns:

func head()

public func head(): HttpRequestBuilder

Description: Constructs a shortcut request function whose request method is "HEAD".

Returns:

func header(String, String)

public func header(name: String, value: String): HttpRequestBuilder

Description: Adds a specified key-value pair to the request header according to the same rule as that of the add function of the HttpHeaders class.

Parameters:

  • name: String: key of the request header
  • value: String: value of the request header

Returns:

Throws:

  • HttpException: If the input name or value contains invalid elements, this exception is thrown.

func method(String)

public func method(method: String): HttpRequestBuilder

Description: Sets the request method. The default request method is "GET".

Parameters:

  • method: String: request method, which must consist of token characters. If an empty string is input, the method value is automatically set to "GET".

Returns:

Throws:

  • HttpException: If the parameter method is invalid, this exception is thrown.

func options()

public func options(): HttpRequestBuilder

Description: Constructs a shortcut request function whose request method is "OPTIONS".

Returns:

func post()

public func post(): HttpRequestBuilder

Description: Constructs a shortcut request function whose request method is "POST".

Returns:

func priority(Int64, Bool)

public func priority(urg: Int64, inc: Bool): HttpRequestBuilder

Description: Sets the shortcut function for a priority header. Calling this function generates a priority header, for example, "priority: urgency=x, i". If the priority field is set by using the function for setting the request header, calling this function is invalid. If this function is called for multiple times, the last call prevails.

Parameters:

  • urg: Int64: request priority. The value ranges from 0 to 7, where 0 indicates the highest priority.
  • inc: Bool: whether incremental request processing is required. If the value is true, the server needs to concurrently process requests with the same urg and inc. If the value is false, the server does not concurrently process requests.

Returns:

func put()

public func put(): HttpRequestBuilder

Description: Constructs a shortcut request function whose request method is "PUT".

Returns:

func readTimeout(Duration)

public func readTimeout(timeout: Duration): HttpRequestBuilder

Description: Sets the read timeout of the request. If the input Duration is negative, it is automatically converted to 0. If the read timeout is set, it is used for the request. If not, the timeout of the request is subject to the Client.

Parameters:

  • timeout: Duration: read timeout of the request set by the user

Returns:

func setHeaders(HttpHeaders)

public func setHeaders(headers: HttpHeaders): HttpRequestBuilder

Description: Sets the request header. If it has been set, calling this function replaces the original header.

Parameters:

Returns:

func setTrailers(HttpHeaders)

public func setTrailers(trailers: HttpHeaders): HttpRequestBuilder

Description: Sets the request trailer. If it has been set, calling this function replaces the original trailer.

Parameters:

Returns:

func trace()

public func trace(): HttpRequestBuilder

Description: Constructs a shortcut request function whose request method is "TRACE".

Returns:

func trailer(String, String)

public func trailer(name: String, value: String): HttpRequestBuilder

Description: Adds a specified key-value pair to the request trailer according to the same rule as that of the add function of the HttpHeaders class.

Parameters:

  • name: String: key of the request header
  • value: String: value of the request header

Returns:

Throws:

  • HttpException: If the input name or value contains invalid elements, this exception is thrown.

func url(String)

public func url(rawUrl: String): HttpRequestBuilder

Description: Sets the request URL. By default, the URL is an empty URL object.

Parameters:

  • rawUrl: String: string to be parsed into a URL object. For details about the string format, see the URL.parse function.

Returns:

Throws:

  • IllegalArgumentException: When the encoded character does not comply with the UTF-8 byte sequence rule, this exception is thrown.

func url(URL)

public func url(url: URL): HttpRequestBuilder

Description: Sets the request URL. By default, the URL is an empty URL object, that is, URL.parse("").

Parameters:

  • url: URL: URL object

Returns:

func version(Protocol)

public func version(version: Protocol): HttpRequestBuilder

Description: Sets the HTTP protocol version of a request. The default version is UnknownProtocol(""). A client automatically selects a protocol according to the TLS configuration.

Parameters:

Returns:

func writeTimeout(Duration)

public func writeTimeout(timeout: Duration): HttpRequestBuilder

Description: Sets the write timeout of the request. If the input Duration is negative, it is automatically converted to 0. If the write timeout is set, it is used for the request. If not, the write timeout of the request is subject to the Client.

Parameters:

  • timeout: Duration: write timeout of the request set by the user

Returns:

class HttpResponse

public class HttpResponse <: ToString

Description: Specifies the HTTP response class.

This class defines the interfaces related to response in HTTP and enables a client to read the response returned by the server.

Parent Type:

prop body

public prop body: InputStream

Description: Obtains a body.

Note:

  • The body does not support concurrent read.
  • By default, the read function of the InputStream implementation class does not support multiple reads.

Type: InputStream

prop bodySize

public prop bodySize: Option<Int64>

Description: Obtains the length of a response body.

  • If the body is not set, bodySize is Some(0).
  • If the body length is known, that is, the body is input through Array<UInt8> or String, or the input InputStream has a definite length (length >= 0), bodySize is Some(Int64).
  • If the body length is unknown, that is, the body is input through a user-defined InputStream instance and the InputStream instance does not have a definite length (length < 0), bodySize is None.

Type: Option<Int64>

prop close

public prop close: Bool

Description: Specifies whether the response header contains Connection: close.

For the server, if close is set to** true**, the connection is closed after the request is fulfilled.

For a client, if close is set to true, the client needs to close the connection if the server does not close the connection after receiving the response.

Type: Bool

prop headers

public prop headers: HttpHeaders

Description: Obtains headers. For details about headers, see the HttpHeaders class. After headers are obtained, the HttpHeaders instance function can be called to modify headers of the request.

Type: HttpHeaders

prop request

public prop request: Option<HttpRequest>

Description: Obtains the request corresponding to the response. The default value is None.

Type: Option<HttpRequest>

prop status

public prop status: UInt16

Description: Obtains the status code of a response. The default value is 200. A status code consists of three digits ranging from 100 to 599. For details, see RFC 9110.

Type: UInt16

prop trailers

public prop trailers: HttpHeaders

Description: Obtains trailers. For details about trailers, see the HttpHeaders class. After trailers are obtained, the HttpHeaders instance function can be called to modify trailers of the request.

Type: HttpHeaders

prop version

public prop version: Protocol

Description: Obtains the protocol version of a response. The default value is HTTP1_1.

Type: Protocol

func getPush()

public func getPush(): ?ArrayList<HttpResponse>

Description: Obtains the server push response. If None is returned, the server push function is disabled. If an empty ArrayList is returned, no response is pushed by the server.

Returns:

func toString()

public override func toString(): String

Description: Converts a response to a string, including status-line, headers, body size, and trailers.

For example, HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nbody size: 5\r\nbar: foo\r\n.

Returns:

  • String: string representation of the response

class HttpResponseBuilder

public class HttpResponseBuilder {
    public init()
}

Description: Constructs an HttpResponse instance.

init()

public init()

Description: Constructs a new HttpResponseBuilder.

func addHeaders(HttpHeaders)

public func addHeaders(headers: HttpHeaders): HttpResponseBuilder

Description: Adds the key-value pairs in HttpHeaders to the response header.

Parameters:

Returns:

func addTrailers(HttpHeaders)

public func addTrailers(trailers: HttpHeaders): HttpResponseBuilder

Description: Adds the key-value pairs in HttpHeaders to the response trailer.

Parameters:

Returns:

func body(Array<UInt8>)

public func body(body: Array<UInt8>): HttpResponseBuilder

Description: Sets the response body. If it has been set, calling this function replaces the original body.

Parameters:

  • body: Array<UInt8>: response body in byte array format

Returns:

func body(InputStream)

public func body(body: InputStream): HttpResponseBuilder

Description: Sets the response body. If it has been set, calling this function replaces the original body.

Parameters:

Returns:

func body(String)

public func body(body: String): HttpResponseBuilder

Description: Sets the response body. If it has been set, calling this function replaces the original body. If this function is called to set the request body, the body is represented by the built-in InputStream implementation class, and its size is known.

Parameters:

  • body: String: response body in string format

Returns:

func build()

public func build(): HttpResponse

Description: Generates an HttpResponse instance based on the HttpResponseBuilder instance.

Returns:

func header(String, String)

public func header(name: String, value: String): HttpResponseBuilder

Description: Adds a specified key-value pair to the response header according to the same rule as that of the add function of the HttpHeaders class.

Parameters:

  • name: String: key of the response header
  • value: String: value of the response header

Returns:

Throws:

  • HttpException: If the input name or value contains invalid elements, this exception is thrown.

func request(HttpRequest)

public func request(request: HttpRequest): HttpResponseBuilder

Description: Sets the request corresponding to the response.

Parameters:

  • request: HttpRequest: request corresponding to the response

Returns:

func setHeaders(HttpHeaders)

public func setHeaders(headers: HttpHeaders): HttpResponseBuilder

Description: Sets the response header. If it has been set, calling this function replaces the original header.

Parameters:

Returns:

func setTrailers(HttpHeaders)

public func setTrailers(trailers: HttpHeaders): HttpResponseBuilder

Description: Sets the response trailer. If it has been set, calling this function replaces the original trailer.

Parameters:

Returns:

func status(UInt16)

public func status(status: UInt16): HttpResponseBuilder

Description: Sets the HTTP response status code.

Parameters:

  • status: UInt16: value of the status code input

Returns:

Throws:

  • HttpException: If the response status code is beyond the range from 100 to 599, this exception is thrown.

func trailer(String, String)

public func trailer(name: String, value: String): HttpResponseBuilder

Description: Adds a specified key-value pair to the response trailer according to the same rule as that of the add function of the HttpHeaders class.

Parameters:

  • name: String: key of the response header
  • value: String: value of the response header

Returns:

Throws:

  • HttpException: If the input name or value contains invalid elements, this exception is thrown.

func version(Protocol)

public func version(version: Protocol): HttpResponseBuilder

Description: Sets the HTTP response protocol version.

Parameters:

Returns:

class HttpResponsePusher

public class HttpResponsePusher

Description: Sets the HTTP/2 server push.

Note:

After receiving the request, if the server considers that the client needs some associated resources later, the server may push the resources to the client in advance. A server push consists of a push request and a push response. To enable server push, call the push function to send a push request and register the handler corresponding to the request with the server to generate a push response. A client can be configured to reject push from the server. Nested push is not allowed, that is, the push cannot be sent again in the handler corresponding to the push request. In the case of nested push, the server rejects the push and prints logs.

static func getPusher(HttpContext)

public static func getPusher(ctx: HttpContext): ?HttpResponsePusher

Description: Obtains the HttpResponsePusher instance. If a client rejects the push, None is returned.

Parameters:

Returns:

func push(String, String, HttpHeaders)

public func push(path: String, method: String, header: HttpHeaders): Unit

Description: Sends a push request to a client. path indicates the request address, method indicates the request method, and header indicates the request header.

Parameters:

  • path: String: request address of the push
  • method: String: request method of the push
  • header: HttpHeaders: request header of the push

class HttpResponseWriter

public class HttpResponseWriter {
    public HttpResponseWriter(let ctx: HttpContext)
}

Description: Specifies the HTTP response message body writer, which allows users to control the sending process of the message body.

Note:

When the write function is called for the first time, the header and the body input through parameters are sent immediately. After that, each time the write function is called, the body input through parameters is sent. For HTTP/1.1, if transfer-encoding: chunked is set, a chunk is sent each time the write function is called. For HTTP/2, the specified data is encapsulated and sent each time the write function is called.

HttpResponseWriter(HttpContext)

public HttpResponseWriter(let ctx: HttpContext)

Description: Constructs an HttpResponseWriter instance.

Parameters:

func write(Array<Byte>)

public func write(buf: Array<Byte>): Unit

Description: Sends data in the buf to a client.

Parameters:

Throws:

class NotFoundHandler

public class NotFoundHandler <: HttpRequestHandler {
    public init()
}

Description: Specifies a convenient HTTP request handler and 404 Not Found handler.

Parent Type:

init()

public init()

Description: Constructs a NotFoundHandler object.

func handle(HttpContext)

public func handle(ctx: HttpContext): Unit

Description: Processes HTTP requests and returns status code 404.

Parameters:

class OptionsHandler

public class OptionsHandler <: HttpRequestHandler {
    public init()
}

Description: Specifies a convenient HTTP handler used to process OPTIONS requests. The "Allow: OPTIONS, GET, HEAD, POST, PUT, or DELETE" response header is always returned.

Parent Type:

init()

public init()

Description: Constructs a NotFoundHandler object.

func handle(HttpContext)

public func handle(ctx: HttpContext): Unit

Description: Processes HTTP OPTIONS requests.

Parameters:

class ProtocolService

public abstract class ProtocolService

Description: Specifies an HTTP service instance which provides HTTP services for a single client connection, including parsing client request packets, distributing requests, and sending responses.

prop server

open protected mut prop server: Server

Description: Returns a Server instance and sets it to a bound Server instance. The default implementation is provided.

func serve

protected func serve(): Unit

Description: Processes connection requests from clients. No default implementation is provided.

func closeGracefully

open protected func closeGracefully(): Unit

Description: Gracefully closes a connection. This function is implemented by default and does not require any operation.

func close

open protected func close(): Unit

Description: Forcibly closes a connection. This function is implemented by default and does not require any operation.

class RedirectHandler

public class RedirectHandler <: HttpRequestHandler

Description: Specifies a convenient HTTP handler used to return redirection responses.

Parent Type:

init(String, UInt16)

public init(url: String, code: UInt16)

Description: Specifies the constructor of RedirectHandler.

Parameters:

  • url: String: URL of the Location header in the redirection response
  • code: UInt16: response code of the redirection response

Throws:

  • HttpException: If the URL is empty or the response code is not status code 3XX (except 304), this exception is thrown.

func handle(HttpContext)

public func handle(ctx: HttpContext): Unit

Description: Processes HTTP requests and returns redirection responses.

Parameters:

class Server

public class Server

Description: Specifies the Server class that provides the HTTP service.

Note:

  • Enabling the service: waits for the user connection and responds to the user's HTTP request at the specified address and port.
  • Disabling the service, including closing all existing connections.
  • A mechanism for registering handlers for processing HTTP requests is provided, which distributes requests to corresponding handlers according to registration information.
  • The TLS certificate hot update mechanism is provided.
  • The shutdown callback mechanism is provided.
  • The Logger.level is used to enable or disable log printing, including printing logs of the corresponding level as required.
  • If the Server document does not specify the supported version, the configuration is valid in both HTTP/1.1 and HTTP/2.

prop addr

public prop addr: String

Description: Obtains the listening address of the server in IP or domain name format.

Type: String

prop distributor

public prop distributor: HttpRequestDistributor

Description: Obtains the request distributor which distributes requests to corresponding handlers according to URLs.

Type: HttpRequestDistributor

prop enableConnectProtocol

public prop enableConnectProtocol: Bool

Description: Specifies whether the packets sent by the peer end support the protocol upgrade using the connect method. The value true indicates that the protocol upgrade using the connect method is supported. This is valid only for HTTP/2.

Type: Bool

prop headerTableSize

public prop headerTableSize: UInt32

Description: Obtains the initial value of the HTTP/2 Hpack dynamic table on the server. The default value is 4096.

Type: UInt32

prop httpKeepAliveTimeout

public prop httpKeepAliveTimeout: Duration

Description: Obtains the timeout set on the server for maintaining a persistent connection. This is valid only for HTTP/1.1.

Type: Duration

prop initialWindowSize

public prop initialWindowSize: UInt32

Description: Limits the initial window size of the packet stream sent by the peer end. This is valid only for HTTP/2. The default value is 65535. The value ranges from 0 to 2^31 – 1.

Type: UInt32

prop listener

public prop listener: ServerSocket

Description: Obtains the socket bound to the server.

Type: ServerSocket

prop logger

public prop logger: Logger

Description: Obtains the server-side logger. The setting of logger.level takes effect immediately. The logger should be thread-safe.

Type: Logger

prop maxConcurrentStreams

public prop maxConcurrentStreams: UInt32

Description: Specifies the maximum number of requests that can be concurrently processed by a connection. This is valid only for HTTP/2.

Type: UInt32

prop maxFrameSize

public prop maxFrameSize: UInt32

Description: Specifies the maximum length of a frame in a packet sent by the peer end. This is valid only for HTTP/2. The default value is 16384. The value ranges from 2^14 to 2^24 – 1.

Type: UInt32

prop maxHeaderListSize

public prop maxHeaderListSize: UInt32

Description: Obtains the maximum header size of HTTP/2 supported by a client. The size refers to the sum of the maximum allowed lengths of all header fields in the response header, including the lengths of all field names and field values, and pseudo header overhead automatically added to each field. (Generally, each field has a 32-byte overhead, including the pseudo header information added by the HTTP/2 protocol to the header field.) By default, this maximum length is set to UInt32.Max.

Type: UInt32

prop maxRequestBodySize

public prop maxRequestBodySize: Int64

Description: Obtains the maximum size of the request body of a read request set by the server. This is valid only for HTTP/1.1 requests without "Transfer-Encoding: chunked" set.

Type: Int64

prop maxRequestHeaderSize

public prop maxRequestHeaderSize: Int64

Description: Obtains the maximum size of the request header of a read request set by the server. This is valid only for HTTP/1.1. For HTTP/2, maxHeaderListSize is applicable.

Type: Int64

prop port

public prop port: UInt16

Description: Obtains the listening port of the server.

Type: UInt16

prop protocolServiceFactory

public prop protocolServiceFactory: ProtocolServiceFactory

Description: Obtains the protocol service factory which generates the service instances required by each protocol.

Type: ProtocolServiceFactory

prop readHeaderTimeout

public prop readHeaderTimeout: Duration

Description: Obtains the timeout for reading a request header set by the server.

Type: Duration

prop readTimeout

public prop readTimeout: Duration

Description: Obtains the timeout for reading the entire request set by the server.

Type: Duration

prop servicePoolConfig

public prop servicePoolConfig: ServicePoolConfig

Description: Obtains the coroutine pool configuration instance.

Type: ServicePoolConfig

prop transportConfig

public prop transportConfig: TransportConfig

Description: Obtain the transport layer configuration set by the server.

Type: TransportConfig

prop writeTimeout

public prop writeTimeout: Duration

Description: Obtains the write response timeout set by the server.

Type: Duration

func afterBind(()->Unit)

public func afterBind(f: ()->Unit): Unit

Description: Registers the callback function on server startup. This function is called after the ServerSocket instance bind is called and before accept is called. Repeatedly calling this function overwrites the previously registered function.

Parameters:

  • f: () ->Unit: callback function. The input parameter is empty, and the return value is of the Unit type.

func close()

public func close(): Unit

Description: Closes the server. After the server is closed, it does not read or process requests. If the server is closed repeatedly (using close or closeGracefully), only the first operation takes effect.

func closeGracefully()

public func closeGracefully(): Unit

Description: Closes the server. After the server is closed, it does not read requests. If the server is processing a request, it will be closed after the processing is complete.

func getTlsConfig()

public func getTlsConfig(): ?TlsServerConfig

Description: Obtains the TLS layer configuration set by the server.

Returns:

  • ?TlsClientConfig: TLS layer configuration set by the client. If it is not set, None is returned.

func onShutdown(()->Unit)

public func onShutdown(f: ()->Unit): Unit

Description: Registers the callback function on server shutdown. This callback function is called on server shutdown. Repeatedly calling this function overwrites the previously registered function.

Parameters:

  • f: () ->Unit: callback function. The input parameter is empty, and the return value is of the Unit type.

func serve()

public func serve(): Unit

Description: Starts the server process. Repeated startup is not supported.

h1 request check and processing:

  • If the request-line does not comply with the request-line = method SP request-target SP HTTP-version rule in RFC 9112, response code 400 is returned.
  • The method consists of tokens and is case-sensitive. The request-target is the URL that can be parsed. The HTTP-version is HTTP/1.0 or HTTP/1.1. Otherwise, response code 400 is returned.
  • The headers name and value must comply with specific rules. Otherwise, status code 400 is returned. For details, see the description of the HttpHeaders class.
  • When the size of headers exceeds the value of maxRequestHeaderSize set by the server, response code 431 is automatically returned.
  • The headers must contain the "host" request header and the value must be unique. Otherwise, response code 400 is returned. The "content-length" and "transfer-encoding" request headers cannot coexist in the headers. Otherwise, response code 400 is returned.
  • After the value of the request header "transfer-encoding" is separated by commas (,), the last value must be "chunked" and the previous values cannot be "chunked". Otherwise, response code 400 is returned.
  • The value of "content-length" in the request header must support parsing to the Int64 type and cannot be a negative value. Otherwise, response code 400 is returned. When the value exceeds the value of maxRequestBodySize set by the server, response code 413 is returned.
  • If "content-length" and "transfer-encoding: chunked" do not exist in headers, no body exists by default.
  • The value of the request header "trailer" cannot contain "transfer-encoding", "trailer", or "content-length".
  • If the value of the request header "expect" contains values other than "100-continue", status code 417 is returned.
  • HTTP/1.0 uses non-persistent connections by default. To keep a persistent connection, you need to include the request headers "connection: keep-alive" and "keep-alive: timeout = XX, max = XX", which will keep the connection alive within the specified timeout period. HTTP/1.1 uses persistent connection by default. If the request fails to be parsed, the connection is closed.
  • The trailer can exist only in chunked mode, and the name of an entry in the trailer must be contained in the "trailer" request header. Otherwise, the entry is automatically deleted.

h1 response check and processing:

  • If the user does not configure response, response code 200 is automatically returned.
  • If the received request contains the request header "connection: close" but the response header "connection" is not added during response configuration or the value of the response header "connection" does not contain "close", "connection: close" is automatically added. If the received request does not contain the request header "connection: close" and the response header does not contain "connection: keep-alive", "connection: close" is automatically added.
  • If headers contain a hop-by-hop response header, such as "proxy-connection", "keep-alive", "te", "transfer-encoding", or "upgrade", such header is automatically added to the response header "connection" as a value.
  • The response header "date" is automatically added, and the "date" provided by the user is ignored.
  • If the request method is "HEAD" or the response status code is "1XX", "204", or "304", the body is left empty.
  • If the body length is known, it is compared with the response header "content-length". If the response header "content-length" does not exist, it is automatically added with its value being the body length. If the length of the response header "content-length" is greater than the body length, HttpException is thrown in the handler. If it is less than the body length, the body is truncated and the length of the sent body is the value of "content-length".
  • The "set-cookie" headers in the response are sent separately, while other headers with the same name are combined for sending.
  • When a request that contains the request header "expect: 100-continue" is processed, response code 100 is automatically sent to the client when body.read() of the request is called. Users are not allowed to send response whose status code is 100. If such response is sent, the server is considered abnormal.

To enable the h2 service, the value of supportedAlpnProtocols in tlsConfig must contain "h2". If the result of ALPN negotiation at the TLS layer is h2, the h2 service is enabled.

h2 request check and processing:

  • The headers name and value must comply with specific rules. For details, see the description of the HttpHeaders class. In addition, the name cannot contain uppercase characters. Otherwise, the RST frame is sent to close the stream, that is, the response cannot be guaranteed.
  • The trailers name and value must comply with the same rules. Otherwise, the stream is closed.
  • The headers cannot contain "connection", "transfer-encoding", "keep-alive", "upgrade", or "proxy-connection." Otherwise, the stream is closed.
  • If the "te" header exists, its value must be "trailers". Otherwise, the stream is closed.
  • If the "host" header and ":authority" pseudo header exist, the value of "host" must be the same as that of ":authority". Otherwise, the stream is closed.
  • If the "content-length" header exists, each value of "content-length" must support parsing to the Int64 type. If there are multiple values, the values must be the same. Otherwise, the stream is closed.
  • If the "content-length" header and the body exist, the value of "content-length" must be the same as the body size. Otherwise, the stream is closed.
  • If the "trailer" header exists, its value cannot contain "transfer-encoding", "trailer", or "content-length". Otherwise, the stream is closed.
  • The CONNECT method is supported only in the WebSocket upgrade scenario. Otherwise, the stream is closed.
  • The pseudo headers must contain ":method", ":scheme", and ":path". The value of ":method" must consist of tokens, the value of ":scheme" must be "https", and the value of ":path" cannot be empty. Otherwise, the stream is closed.
  • The name of an entry in the trailer must be included in the "trailer" header. Otherwise, the entry is automatically deleted.
  • The size of request headers cannot exceed the value of maxHeaderListSize. Otherwise, the connection is closed.

h2 response check and processing:

  • If the response to the HEAD request contains a body, the body is automatically deleted.
  • The "date" field is automatically added, and the "date" provided by the user is ignored.
  • "connection", "transfer-encoding", "keep-alive", "upgrade", or "proxy-connection" contained in headers is automatically deleted.
  • The "set-cookie" headers in the response are sent separately, while other headers with the same name are combined for sending.
  • If headers contain "content-length" and the request method is not "HEAD", "content-length" is deleted.
  • If the request method is "HEAD," then:
    • If the headers contain "content-length" but "content-length" is invalid (it cannot be parsed to an Int64 value or contains multiple different values), HttpException is thrown when the user calls the write function of the HttpResponseWriter class to trigger verification. If the user does not perform such operation, logs are printed.
    • If the headers contain "content-length", response.body.length is not –1, and the value of "content-length" is inconsistent with that of body.length, the handling method is the same as that in 6.1.
    • If the headers contain "content-length" and response.body.length is –1, or the value of body.length is the same as that of "content-length", the "content-length" header is retained.
  • The entries in the trailer must be included in the "trailer" header. Otherwise, the entries are automatically deleted.
  • If an exception is thrown in the handler and the user does not call the write function to send partial response, response code 500 is returned. If the user has called the write function to send partial response, the RST frame is sent to close the stream.

After the h2 server sends a response, if the stream status is not CLOSED, the h2 server sends an RST frame with the NO_ERROR error code to close the stream to prevent the processed stream from occupying server resources.

h2 flow control:

  • The initial value of the connection flow window is 65535. Each time a DATA frame is received, WINDOW-UPDATE at the connection layer is returned. When data is sent, if the value of the connection flow window is negative, the thread that sends data is blocked until the value becomes positive.
  • The initial value of the stream flow window can be set by the user. The default value is 65535. Each time a DATA frame is received, WINDOW-UPDATE at the stream layer is returned. When data is sent, if the value of the stream flow window is negative, the thread that sends data is blocked until the value becomes positive.

h2 request priority:

  • Requests can be processed by urgency. By default, the h2 service processes requests concurrently. When concurrent resources are insufficient, requests are processed by urgency. Requests with a higher priority are processed preferentially.

Default ProtocolServiceFactory protocol options:

  • For TCP connections, the HTTP/1.1 server is used.
  • For TLS connections, the HTTP protocol version is determined based on the result of ALPN negotiation. If the negotiation result is "HTTP/1.0", "HTTP/1.1", or "", the HTTP/1.1 server is used. If the negotiation result is "h2", the HTTP/2 server is used. Otherwise, the request is not processed, logs are printed, and the connection is closed.

Throws:

func updateCA(Array<X509Certificate>)

public func updateCA(newCa: Array<X509Certificate>): Unit

Description: Performs hot update for the CA certificate.

Parameters:

Throws:

func updateCA(String)

public func updateCA(newCaFile: String): Unit

Description: Performs hot update for the CA certificate.

Parameters:

  • newCaFile: String: CA certificate file

Throws:

func updateCert(Array<X509Certificate>, PrivateKey)

public func updateCert(certChain: Array<X509Certificate>, certKey: PrivateKey): Unit

Description: Performs hot update for the TLS certificate.

Parameters:

Throws:

  • HttpException: If tlsConfig is not configured on the server, this exception is thrown.

func updateCert(String, String)

public func updateCert(certificateChainFile: String, privateKeyFile: String): Unit

Description: Performs hot update for the TLS certificate.

Parameters:

  • certificateChainFile: String: certificate chain file
  • privateKeyFile: String: certificate-matched private key file

Throws:

class ServerBuilder

public class ServerBuilder {
    public init()
}

Description: Provides a Server instance constructor.

The following parameters can be used to construct an HTTP Server:

  • IP address or port
  • Thread-safe logger
  • HttpRequestDistributor, which is used to register handlers and distribute requests
  • HTTP/2 settings
  • shutdown callback
  • transport, including the listener, connection, and configuration
  • protocol service, which provides the HTTP protocol parsing service

Default implementation is provided for parameters except for address, port, and shutdown callback. The user does not need to specify other parameters when constructing the server. If the ServerBuilder document does not specify the supported version, the configuration is valid in both HTTP/1.1 and HTTP/2.

init()

public init()

Description: Creates a ServerBuilder instance.

func addr(String)

public func addr(addr: String): ServerBuilder

Description: Sets the listening address of the server. If the listener is set, this value is ignored.

Parameters:

  • addr: String: address in IP or domain name format

Returns:

func afterBind(()->Unit)

public func afterBind(f: ()->Unit): ServerBuilder

Description: Registers the callback function on server startup. This function is called after the ServerSocket instance bind is called and before accept is called. Repeatedly calling this function overwrites the previously registered function.

Parameters:

  • f: () ->Unit: callback function. The input parameter is empty, and the return value is of the Unit type.

Returns:

func build()

public func build(): Server

Description: Constructs a Server instance based on the configured attributes.

Returns:

Throws:

func distributor(HttpRequestDistributor)

public func distributor(distributor: HttpRequestDistributor): ServerBuilder

Description: Sets the request distributor which distributes requests to corresponding handlers according to URLs. If this parameter is not set, the default request distributor is used.

Parameters:

Returns:

func enableConnectProtocol(Bool)

public func enableConnectProtocol(flag: Bool): ServerBuilder

Description: Specifies whether the local end receives CONNECT requests. The default value is false. This is valid only for HTTP/2.

Parameters:

  • flag: Bool: whether the local end receives the CONNECT request

Returns:

func headerTableSize(UInt32)

public func headerTableSize(size: UInt32): ServerBuilder

Description: Sets the initial value of the HTTP/2 Hpack dynamic table on the server. The default value is 4096.

Parameters:

  • size: UInt32: maximum table size used by the local end to encode the response header

Returns:

func httpKeepAliveTimeout(Duration)

public func httpKeepAliveTimeout(timeout: Duration): ServerBuilder

Description: Specifies the keepalive duration of a connection on the server. If a client does not send a request again within the keepalive duration, the server closes the persistent connection. By default, the interval of sending requests is not limited. This is valid only for HTTP/1.1.

Parameters:

  • timeout: Duration: timeout for maintaining a persistent connection. A negative value of the Duration is replaced with Duration.Zero.

Returns:

func initialWindowSize(UInt32)

public func initialWindowSize(size: UInt32): ServerBuilder

Description: Specifies the initial window size for receiving packets of each stream on the current server. The default value is 65535. This is valid only for HTTP/2. The value ranges from 0 to 2^31 – 1.

Parameters:

  • size: UInt32: initial window size for receiving packets of a stream on the local end

Returns:

func listener(ServerSocket)

public func listener(listener: ServerSocket): ServerBuilder

Description: The server calls this function to bind and listen to a specified socket.

Parameters:

Returns:

func logger(Logger)

public func logger(logger: Logger): ServerBuilder

Description: Sets the server-side logger. The default logger level is INFO. The logger content is written to Console.stdout.

Parameters:

  • logger: Logger: The logger must be thread-safe. By default, the built-in thread-safe logger is used.

Returns:

func maxConcurrentStreams(UInt32)

public func maxConcurrentStreams(size: UInt32): ServerBuilder

Description: Sets the maximum number of requests that can be concurrently processed by the local end and the number of requests that can be concurrently sent by the peer end. The default value is 100. This is valid only for HTTP/2.

Parameters:

  • size: UInt32: maximum number of requests that can be concurrently processed by the local end

Returns:

func maxFrameSize(UInt32)

public func maxFrameSize(size: UInt32): ServerBuilder

Description: Sets the maximum length of a frame received by the local end to limit the length of a frame sent by the peer end. The default value is 16384. This is valid only for HTTP/2. The value ranges from 2^14 to 2^24 – 1.

Parameters:

  • size: UInt32: maximum length of a frame received by the local end

Returns:

func maxHeaderListSize(UInt32)

public func maxHeaderListSize(size: UInt32): ServerBuilder

Description: Obtains the maximum header size of HTTP/2 supported by a client. The size refers to the sum of the maximum allowed lengths of all header fields in the response header, including the lengths of all field names and field values, and pseudo header overhead automatically added to each field. (Generally, each field has a 32-byte overhead, including the pseudo header information added by the HTTP/2 protocol to the header field.) By default, this maximum length is set to UInt32.Max.

Parameters:

  • size: UInt32: maximum length of a packet header received by the local end

Returns:

func maxRequestBodySize(Int64)

public func maxRequestBodySize(size: Int64): ServerBuilder

Description: Sets the maximum length of a request body that the server allows a client to send. If the length of a request body exceeds this value, response code 413 is returned. The default value is 2 MB. This is valid only for HTTP/1.1 requests without "Transfer-Encoding: chunked" set.

Parameters:

  • size: Int64: maximum size of a request body that can be received. The value 0 indicates that the size is not limited.

Returns:

Throws:

func maxRequestHeaderSize(Int64)

public func maxRequestHeaderSize(size: Int64): ServerBuilder

Description: Sets the maximum length of a request header that the server allows a client to send. If the length of a request header exceeds this value, response code 431 is returned. This is valid only for HTTP/1.1. For HTTP/2, maxHeaderListSize is applicable.

Parameters:

  • size: Int64: maximum size of a request header that can be received. The value 0 indicates that the size is not limited.

Returns:

Throws:

func onShutdown(()->Unit)

public func onShutdown(f: ()->Unit): ServerBuilder

Description: Registers the callback function on server shutdown. This callback function is called on server shutdown. Repeatedly calling this function overwrites the previously registered function.

Parameters:

  • f: () ->Unit: callback function. The input parameter is empty, and the return value is of the Unit type.

Returns:

func port(UInt16)

public func port(port: UInt16): ServerBuilder

Description: Sets the listening port of the server. If the listener is set, this value is ignored.

Parameters:

Returns:

func protocolServiceFactory(ProtocolServiceFactory)

public func protocolServiceFactory(factory: ProtocolServiceFactory): ServerBuilder

Description: Sets the protocol service factory which generates the service instances required by each protocol. If this parameter is not set, the default factory is used.

Parameters:

Returns:

func readHeaderTimeout(Duration)

public func readHeaderTimeout(timeout: Duration): ServerBuilder

Description: Sets the maximum duration for the server to read the request header of a request sent by a client. If the duration exceeds the value set, no read operation is performed and the connection is closed. By default, the read duration is not limited.

Parameters:

  • timeout: Duration: timeout for reading a request header. A negative value of the Duration is replaced with Duration.Zero.

Returns:

func readTimeout(Duration)

public func readTimeout(timeout: Duration): ServerBuilder

Description: Sets the maximum duration for the server to read a request. If the duration exceeds the value set, no read operation is performed and the connection is closed. By default, the read timeout is not specified.

Parameters:

  • timeout: Duration: timeout for reading a request. A negative value input is replaced with Duration.Zero.

Returns:

func servicePoolConfig(ServicePoolConfig)

public func servicePoolConfig(cfg: ServicePoolConfig): ServerBuilder

Description: Configures the coroutine pool used during service. For details, see the ServicePoolConfig struct.

Parameters:

Returns:

func tlsConfig(TlsServerConfig)

public func tlsConfig(config: TlsServerConfig): ServerBuilder

Description: Sets the TLS layer configuration which is not set by default.

Parameters:

  • config: TlsServerConfig: configuration information required for supporting the TLS service

Returns:

func transportConfig(TransportConfig)

public func transportConfig(config: TransportConfig): ServerBuilder

Description: Sets the transport layer configuration. For details about the default configuration, see the description of the TransportConfig struct.

Parameters:

Returns:

func writeTimeout(Duration)

public func writeTimeout(timeout: Duration): ServerBuilder

Description: Sets the maximum duration for the server to send a response. If the duration exceeds the value set, no write operation is performed and the connection is closed. By default, the write timeout is not specified.

Parameters:

  • timeout: Duration: write response timeout. A negative value input is replaced with Duration.Zero.

Returns:

class WebSocket

public class WebSocket

Description: Provides classes related to the WebSocket service and read, write, and close functions for the WebSocket connection. The user uses the upgradeFrom function to obtain the WebSocket connection.

  • By calling read() to read a WebSocketFrame, the user can know the frame type through WebSocketFrame.frameType and whether the frame is segmented through WebSocketFrame.fin.
  • write(frameType: WebSocketFrameType, byteArray: Array<UInt8>) is called with the message type and message byte passed to send a WebSocket message. If a control frame is written, the message is not sent in fragments. If a data frame (Text or Binary) is written, the message is sent in multiple fragments based on the size of the underlying buffer.

For details, see the following interface description. The interface behavior is subject to RFC 6455.

prop logger

public prop logger: Logger

Description: Specifies a logger.

Type: Logger

prop subProtocol

public prop subProtocol: String

Description: Obtains the subProtocol negotiated with the peer end. During the negotiation, the client provides a list of subProtocols ranked by preference, and the server selects one or zero subprotocols from the list.

Type: String

static func upgradeFromClient(Client, URL, Protocol, ArrayList<String>, HttpHeaders)

public static func upgradeFromClient(client: Client, url: URL,
 version!: Protocol = HTTP1_1,
 subProtocols!: ArrayList<String> = ArrayList<String>(), 
 headers!: HttpHeaders = HttpHeaders()): (WebSocket, HttpHeaders)

Description: Provides a function for an upgrade to the WebSocket protocol on a client.

Note:

The upgrade process on a client is as follows: The client object and URL object are passed to construct an upgrade request. After the request is sent to the server, the client verifies the response. If the handshake is successful, the WebSocket object is returned for WebSocket communication, and the HttpHeaders object with response header 101 is returned to the user. Extensions are not supported. If the subprotocol negotiation is successful, the user can view the subprotocol by calling the subProtocol of returned WebSocket.

Parameters:

  • client: Client: client object used for the request
  • version!: Protocol: HTTP version used to create a socket. Only HTTP1_1 and HTTP2_0 can be upgraded to WebSocket.
  • url: URL: URL object used for the request. During the WebSocket upgrade, the URL scheme must be ws or wss.
  • subProtocols!: ArrayList<String>: user-defined list of subprotocols ranked by preference. It is empty by default. If the user configures the list, it is sent to the server with the update request.
  • headers!: HttpHeaders: optional headers, such as cookies, sent along with the update request

Returns:

  • (WebSocket, HttpHeaders): If the upgrade is successful, the WebSocket object is returned for communication together with the header of response code 101.

Throws:

  • SocketException: If the underlying connection is incorrect, this exception is thrown.
  • HttpException: If an error occurs upon handshake during the HTTP request process, this exception is thrown.
  • WebSocketException: If the upgrade fails, or the upgrade response verification fails, this exception is thrown.

static func upgradeFromServer(HttpContext, ArrayList<String>, ArrayList<String>, (HttpRequest) -> HttpHeaders)

public static func upgradeFromServer(ctx: HttpContext, subProtocols!: ArrayList<String> = ArrayList<String>(), 
                                        origins!: ArrayList<String> = ArrayList<String>(), 
                                        userFunc!:(HttpRequest) -> HttpHeaders = {_: HttpRequest => HttpHeaders()}): WebSocket

Description: Provides a function for an upgrade to the WebSocket protocol on the server. This function is usually used in handlers.

The upgrade process on the server is as follows: After receiving an upgrade request from a client, the server verifies the request. If the verification is successful, the server returns response code 101 and the WebSocket object for WebSocket communication.

  • The user configures the supported subprotocol and origin whitelists by setting the subProtocols and origins parameters. If the subProtocols parameter is not set, subprotocols are not supported. If the origins parameter is not set, handshake requests from all origins are accepted.
  • The user uses userFunc to define the upgrade request processing behavior, such as cookie processing. The input userFunc requires an HttpHeaders object, which is returned to the client through a 101 response. (The object is not returned if the upgrade fails.)
  • WebSocket extensions are not supported currently. Therefore, if extensions negotiation occurs during handshake, WebSocketException is thrown.
  • Only HTTP1_1 and HTTP2_0 can be upgraded to WebSocket.

Parameters:

  • ctx: HttpContext: HTTP request context. Parameters input to the handler are directly passed to upgradeFromServer.
  • subProtocols!: ArrayList<String>: user-defined list of subprotocols. The default value is empty, indicating that subprotocols are not supported. If the user configures the list, the first subprotocol in the upgrade request is used as the subprotocol of the upgraded WebSocket. The user can view the subprotocol by calling the subProtocol of returned WebSocket.
  • origins!: ArrayList<String>: user-defined list of origins from which handshakes are accepted. If the list is not defined, handshakes from all origins are accepted. If the list is defined, only handshakes from the origins defined in the list are accepted.
  • userFunc!: (HttpRequest) ->HttpHeaders: user-defined function for processing upgrade requests. This function returns HttpHeaders.

Returns:

func closeConn()

public func closeConn(): Unit

Description: Provides a function for closing the underlying WebSocket connection.

Note:

The underlying connection is directly closed. The close process must comply with the handshake process specified in the protocol. That is, the local end sends a Close frame to the peer end and waits for a Close frame from the peer end. The underlying connection can be closed only after the handshake process is complete.

func read()

public func read(): WebSocketFrame

Description: Reads a frame from a connection. If the data on the connection is not ready, the read thread is blocked. This is not thread-safe. (That is, multi-thread read is not supported for the same WebSocket object.)

The read function returns a WebSocketFrame object. The user can call the frameType and fin attribute of WebSocketFrame to determine the frame type and whether the frame called is segmented. The raw binary data array Array<UInt8> is obtained by using the payload function of WebSocketFrame.

  • For a segmented frame, first segment: fin == false, frameType == TextWebFrame or BinaryWebFrame; intermediate segment: fin == false, frameType == ContinuationWebFrame; tail segment: fin == true, frameType == ContinuationWebFrame.
  • For a non-segmented frame, fin == true, frameType != ContinuationWebFrame.

Note:

  • Data frames (Text or Binary) can be segmented. The user needs to call the read function for multiple times to read all segments (that is, receiving a complete message), and then splice the payloads of the segments in the sequence they are received. The payload of the Text frame is in UTF-8 format. After receiving a complete message, the user calls the String.fromUtf8 function to convert the spliced payload to a string. The meaning of the payload of the binary frame is determined by the application that uses the payload. After receiving the complete message, the user sends the spliced payload to the upper-layer application.
  • Control frames (Close, Ping, and Pong) cannot be segmented.
  • A control frame cannot be segmented, but can be inserted between data frame segments. No other data frame is allowed between data frame segments. Data frame segments with inserted data frames are considered as errors.
  • If the client receives the masked frame, or the server receives the unmasked frame, the underlying connection is interrupted and an exception is thrown.
  • If the rsv1, rsv2, and rsv3 bits are set (extensions are not supported currently, so the rsv bit must be 0), the underlying connection is interrupted and an exception is thrown.
  • If a frame type (other than Continuation, Text, Binary, Close, Ping, and Pong) that is not supported is received, the underlying connection is interrupted and an exception is thrown.
  • If a control frame (Close, Ping, or Pong) whose payload length is greater than 125 bytes or a segmented control frame is received, the underlying connection is interrupted and an exception is thrown.
  • If a frame whose payload length is greater than 20 MB is received, the underlying connection is interrupted and an exception is thrown.
  • If read is called after the connection is closed using closeConn, an exception is thrown.

Returns:

Throws:

  • SocketException: underlying connection error
  • WebSocketException: If a frame that does not comply with the protocol is received, a Close frame is sent to the peer end to indicate the error information and the underlying connection is interrupted.
  • ConnectionException: If data is read from the connection that has been closed by the peer end, this exception is thrown.

func write(WebSocketFrameType, Array<UInt8>, Int64)

public func write(frameType: WebSocketFrameType, byteArray: Array<UInt8>, frameSize!: Int64 = FRAMESIZE): Unit

Description: Sends data. This is not thread-safe. (That is, multi-thread write is not supported for the same WebSocket object.)

Note:

The write function sends data to the peer end in the form of WebSocket frames.

  • If the size of the input byteArray is greater than frameSize (4 x 1024 bytes by default) when a data frame (Text or Binary) is sent, the data frame (text or binary) is divided into payloads whose size is less than or equal to frameSize and sent in segments. Otherwise, the data frame is not segmented.
  • If the size of the input byteArray must be less than or equal to 125 bytes when a control frame (Close, Ping, or Pong) is sent, the first two bytes of the Close frame are status codes. For details about available status codes, see RFC 6455 7.4. According to the Status Codes protocol, after a Close frame is sent, data frames cannot be sent. Otherwise, an exception is thrown.
  • The user needs to ensure that the input byteArray complies with the protocol. For example, the payload of the Text frame must be encoded in UTF-8 format. If frameSize is set for the data frame, the value must be greater than 0. Otherwise, an exception is thrown.
  • If the value of frameSize is less than or equal to 0 when a data frame is sent, an exception is thrown.
  • If the input data is greater than 125 bytes when the user sends a control frame, an exception is thrown.
  • If the user inputs a frame type other than Text, Binary, Close, Ping, and Pong type, an exception is thrown.
  • If an invalid status code is input when the Close frame is sent or the reason data exceeds 123 bytes, an exception is thrown.
  • If data frames are sent after the Close frame is sent, an exception is thrown.
  • If write is called after the connection is closed using closeConn, an exception is thrown.

Parameters:

  • frameType: WebSocketFrameType: type of the frame to be sent
  • byteArray: Array<UInt8>: payload (in binary format) of the frame to be sent
  • frameSize!: Int64: size of the frame segment. The default size is 4 x 1024 bytes. The frameSize is not valid for control frames.

Throws:

  • SocketException: If the underlying connection is incorrect, this exception is thrown.
  • WebSocketException: If the input frame type or data is invalid, this exception is thrown.

func writeCloseFrame(?UInt16, String)

public func writeCloseFrame(status!: ?UInt16 = None, reason!: String = ""): Unit

Description: Sends the Close frame.

Note:

According to the protocol, data frames cannot be sent after the Close frame is sent. If the user does not set the status, the reason is not sent (that is, the reason must be sent with the status). The payload of the control frame does not exceed 125 bytes. The first two bytes of the Close frame are the status. Therefore, the reason cannot exceed 123 bytes. If write is called after the connection is closed using closeConn, an exception is thrown.

Parameters:

  • status!: ?UInt16: status code of the Close frame sent. The default value is None, indicating that the status code and reason are not sent.
  • reason!: String: description of closing a connection. This parameter is an empty string by default, and it is converted to UTF-8 when being sent. This parameter is used for debugging, and it may be unreadable.

Throws:

  • WebSocketException: If an invalid status code is input or the reason data exceeds 123 bytes, this exception is thrown.

func writePingFrame(Array<UInt8>)

public func writePingFrame(byteArray: Array<UInt8>): Unit

Description: Provides a shortcut function for sending Ping frames. If write is called after the connection is closed using closeConn, an exception is thrown.

Parameters:

  • byteArray: Array<UInt8>: payload (in binary format) of the frame to be sent

Throws:

  • SocketException: If the underlying connection is incorrect, this exception is thrown.
  • WebSocketException: If the input data is greater than 125 bytes, this exception is thrown.

func writePongFrame(Array<UInt8>)

public func writePongFrame(byteArray: Array<UInt8>): Unit

Description: Provides a shortcut function for sending Pong frames. If write is called after the connection is closed using closeConn, an exception is thrown.

Parameters:

  • byteArray: Array<UInt8>: payload (in binary format) of the frame to be sent

Throws:

  • SocketException: If the underlying connection is incorrect, this exception is thrown.
  • WebSocketException: If the input data is greater than 125 bytes, this exception is thrown.

class WebSocketFrame

public class WebSocketFrame

Description: Specifies the basic unit used by WebSocket for read.

WebSocketFrame provides three attributes, where fin and frameType indicate the frame type and whether the frame is segmented. Payload is the payload of the frame.

  • For a segmented frame, first segment: fin == false, frameType == TextWebFrame or BinaryWebFrame;
  • intermediate segment: fin == false, frameType == ContinuationWebFrame;
  • tail segment: fin == true, frameType == ContinuationWebFrame.
  • For a non-segmented frame, fin == true, frameType != ContinuationWebFrame.
  • The user can obtain WebSocketFrame only by calling the read function of the WebSocket object. Data frames can be segmented. If the user receives a segmented frame, the read function must be called for multiple times until a complete message is received, and the payloads of all segments must be spliced in the sequence they are received.

Note:

Since the control frame may be inserted between frame segments, the user needs to separately process the control frame when splicing the payloads of frame segments. Only control frames can be inserted between frame segments. Other data frames between frame segments are considered as errors.

prop fin

public prop fin: Bool

Description: Obtains the fin attribute of WebSocketFrame. fin and frameType indicate the frame type and whether the frame is segmented.

Type: Bool

prop frameType

public prop frameType: WebSocketFrameType

Description: Obtains the frame type of WebSocketFrame. fin and frameType indicate the frame type and whether the frame is segmented.

Type: WebSocketFrameType

prop payload

public prop payload: Array<UInt8>

Description: Obtains the frame payload of WebSocketFrame. For a segmented data frame, after receiving a complete message, the user needs to splice the payloads of all segments in the sequence they are received.

Type: Array<UInt8>