目录

类

class Client

public class Client

功能:发送 Http request、随时关闭等。用户可以通过 Client 实例发送 HTTP/1.1 或 HTTP/2 请求。

Client 文档中未明确说明支持版本的配置,在 HTTP/1.1 与 HTTP/2 都会生效。

[h2]prop autoRedirect

public prop autoRedirect: Bool

功能:客户端是否会自动进行重定向,304 状态码默认不重定向。

类型:Bool

[h2]prop connector

public prop connector: (String) -> StreamingSocket

功能:客户端调用此函数获取到服务器的连接。

类型:(String) -> StreamingSocket

[h2]prop cookieJar

public prop cookieJar: ?CookieJar

功能:用于存储客户端所有 Cookie,如果配置为 None,则不会启用 Cookie。

类型:?CookieJar

[h2]prop enablePush

public prop enablePush: Bool

功能:客户端 HTTP/2 是否支持服务器推送,默认值为 true。

类型:Bool

[h2]prop headerTableSize

public prop headerTableSize: UInt32

功能:获取客户端 HTTP/2 Hpack 动态表的初始值,默认值为 4096。

类型:UInt32

[h2]prop httpProxy

public prop httpProxy: String

功能:获取客户端 http 代理,默认使用系统环境变量 http_proxy 的值,用字符串表示,格式为:"http://host:port",例如:"http://192.168.1.1:80"。

类型:String

[h2]prop httpsProxy

public prop httpsProxy: String

功能:获取客户端 https 代理,默认使用系统环境变量 https_proxy 的值,用字符串表示,格式为:"http://host:port",例如:"http://192.168.1.1:443"。

类型:String

[h2]prop initialWindowSize

public prop initialWindowSize: UInt32

功能:获取客户端 HTTP/2 流控窗口初始值,默认值为 65535 ,取值范围为 0 至 2^31 - 1。

类型:UInt32

[h2]prop logger

public prop logger: Logger

功能:获取客户端日志记录器,设置 logger.level 将立即生效,记录器应该是线程安全的。

类型:Logger

[h2]prop maxConcurrentStreams

public prop maxConcurrentStreams: UInt32

功能:获取客户端 HTTP/2 初始最大并发流数量,默认值为 2^31 - 1。

类型:UInt32

[h2]prop maxFrameSize

public prop maxFrameSize: UInt32

功能:获取客户端 HTTP/2 初始最大帧大小。默认值为 16384. 取值范围为 2^14 至 2^24 - 1。

类型:UInt32

[h2]prop maxHeaderListSize

public prop maxHeaderListSize: UInt32

功能:获取客户端支持的 HTTP/2 最大头部(Header)大小。这个大小指的是响应头部中所有头部字段(Header Field)的最大允许长度之和,其中包括所有字段名称(name)的长度、字段值(value)的长度以及每个字段自动添加的伪头开销(通常每个字段会有32字节的开销,这包括了HTTP/2协议本身为头部字段添加的伪头部信息)。默认情况下,这个最大长度被设置为 UInt32.Max。

类型:UInt32

[h2]prop poolSize

public prop poolSize: Int64

功能:配置 HTTP/1.1 客户端使用的连接池的大小,亦可表示对同一个主机(host:port)同时存在的连接数的最大值。

类型:Int64

[h2]prop readTimeout

public prop readTimeout: Duration

功能:获取客户端设定的读取整个响应的超时时间,默认值为 15s。

类型:Duration

[h2]prop writeTimeout

public prop writeTimeout: Duration

功能:获取客户端设定的写请求的超时时间,默认值为 15s。

类型:Duration

[h2]func close()

public func close(): Unit

功能:关闭客户端建立的所有连接,调用后不能继续发送请求。

[h2]func connect(String, HttpHeaders, Protocol)

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

功能:发送 CONNECT 请求与服务器建立隧道,返回建连成功后的连接,连接由用户负责关闭。服务器返回 2xx 表示建连成功,否则建连失败(不支持自动重定向,3xx 也视为失败)。

参数:

返回值:

异常:

[h2]func delete(String)

public func delete(url: String): HttpResponse

功能:请求方法为 DELETE 的便捷请求函数。

参数:

返回值:

异常:

[h2]func get(String)

public func get(url: String): HttpResponse

功能:请求方法为 GET 的便捷请求函数。

参数:

返回值:

异常:

[h2]func getTlsConfig()

public func getTlsConfig(): ?TlsClientConfig

功能:获取客户端设定的 TLS 层配置。

返回值:

[h2]func head(String)

public func head(url: String): HttpResponse

功能:请求方法为 HEAD 的便捷请求函数。

参数:

返回值:

异常:

[h2]func options(String)

public func options(url: String): HttpResponse

功能:请求方法为 OPTIONS 的便捷请求函数。

参数:

返回值:

异常:

[h2]func post(String, Array<UInt8>)

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

功能:请求方法为 POST 的便捷请求函数。

参数:

返回值:

异常:

[h2]func post(String, InputStream)

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

功能:请求方法为 POST 的便捷请求函数。

参数:

返回值:

异常:

[h2]func post(String, String)

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

功能:请求方法为 POST 的便捷请求函数。

参数:

返回值:

异常:

[h2]func put(String, Array<UInt8>)

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

功能:请求方法为 PUT 的便捷请求函数。

参数:

返回值:

异常:

[h2]func put(String, InputStream)

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

功能:请求方法为 PUT 的便捷请求函数。

参数:

返回值:

异常:

[h2]func put(String, String)

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

功能:请求方法为 PUT 的便捷请求函数。

参数:

返回值:

异常:

[h2]func send(HttpRequest)

public func send(req: HttpRequest): HttpResponse

功能:通用请求函数,发送 HttpRequest 到 url 中的服务器,接收 HttpResponse。

  • 对于 HTTP/1.1,如果请求中有 body 要发,那么需要保证 Content-Length 和 Transfer-Encoding: chunked必有且只有一个,以 chunked 形式发时,每段 chunk 最大为 8192 字节;如果用户发送的 body 为自己实现的 InputStream 类,则需要自己保证 Content-Length和 Transfer-Encoding: chunked 设置且只设置了一个;如果用户采用默认的 body 发送,Content-Length 和 Transfer-Encoding: chunked都缺失时,我们会为其补上 Content-Length header,值为 body.size;
  • 用户如果设置了 Content-Length,则需要保证其正确性:如果所发 body 的内容大于等于 Content-Length 的值,我们会发送长度为 Content-Length 值的数据;如果所发 body 的内容小于 Content-Length 的值,此时如果 body 是默认的 body,则会抛出 HttpException,如果 body是用户自己实现的 InputStream 类,其行为便无法保证(可能会造成服务器端的读 request 超时或者客户端的收 response 超时);
  • 升级函数通过 WebSocket 的 upgradeFromClient 或 Client 的 upgrade 接口发出,调用 client 的其他函数发送 upgrade 请求会抛出异常;
  • 协议规定 TRACE 请求无法携带内容,故用户发送带有 body 的 TRACE 请求时会抛出异常;
  • HTTP/1.1 默认对同一个服务器的连接数不超过 10 个。response 的 body 需要用户调用 body.read(buf: Array<Byte>) 函数去读。body 被读完后,连接才能被客户端对象复用,否则请求相同的服务器也会新建连接。新建连接时如果连接数超出限制则会抛出 HttpException;
  • body.read 函数将 body 读完之后返回 0,如果读的时候连接断开会抛出 ConnectionException;
  • HTTP/1.1 的升级请求如果收到 101 响应,则表示切换协议,此连接便不归 client 管理;
  • 下文的快捷请求函数的注意点与 send 相同。

参数:

返回值:

异常:

[h2]func upgrade(HttpRequest)

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

功能:发送请求并升级协议,用户设置请求头,返回升级后的连接(如果升级成功),连接由用户负责关闭。

  • 服务器返回 101 表示升级成功,获取到了 StreamingSocket;
  • 必选请求头:
    • Upgrade: protocol-name ["/" protocol-version];
    • Connection: Upgrade (在请求头包含 Upgrade 字段时会自动添加);
  • 不支持 HTTP/1.0、HTTP/2;
  • 不支持 HTTP/1.1 CONNECT 方法的 HttpRequest。

参数:

返回值:

异常:

class ClientBuilder

public class ClientBuilder {
    public init()
}

功能:用于 Client 实例的构建,Client 没有公开的构造函数,用户只能通过 ClientBuilder 得到 Client 实例。ClientBuilder 文档中未明确说明支持版本的配置,在 HTTP/1.1 与 HTTP/2 都会生效。

[h2]init()

public init()

功能:创建新的 ClientBuilder 实例。

[h2]func autoRedirect(Bool)

public func autoRedirect(auto: Bool): ClientBuilder

功能:配置客户端是否会自动进行重定向。重定向会请求 Location 头的资源,协议规定,Location 只能包含一个 URI 引用Location = URI-reference,详见 RFC 9110 10.2.2.。304 状态码默认不重定向。

参数:

返回值:

[h2]func build()

public func build(): Client

功能:构造 Client 实例。

返回值:

异常:

[h2]func connector((String)->StreamingSocket)

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

功能:客户端调用此函数获取到服务器的连接。

参数:

返回值:

[h2]func cookieJar(?CookieJar)

public func cookieJar(cookieJar: ?CookieJar): ClientBuilder

功能:用于存储客户端所有 Cookie。

参数:

返回值:

[h2]func enablePush(Bool)

public func enablePush(enable: Bool): ClientBuilder

功能:配置客户端 HTTP/2 是否支持服务器推送。

参数:

返回值:

[h2]func headerTableSize(UInt32)

public func headerTableSize(size: UInt32): ClientBuilder

功能:配置客户端 HTTP/2 Hpack 动态表初始值。

参数:

返回值:

[h2]func httpProxy(String)

public func httpProxy(addr: String): ClientBuilder

功能:设置客户端 http 代理,默认使用系统环境变量 http_proxy 的值。

参数:

返回值:

[h2]func httpsProxy(String)

public func httpsProxy(addr: String): ClientBuilder

功能:设置客户端 https 代理,默认使用系统环境变量 https_proxy 的值。

参数:

返回值:

[h2]func initialWindowSize(UInt32)

public func initialWindowSize(size: UInt32): ClientBuilder

功能:配置客户端 HTTP/2 流控窗口初始值。

参数:

返回值:

[h2]func logger(Logger)

public func logger(logger: Logger): ClientBuilder

功能:设定客户端的 logger,默认 logger 级别为 INFO,logger 内容将写入 Console.stdout。

参数:

返回值:

[h2]func maxConcurrentStreams(UInt32)

public func maxConcurrentStreams(size: UInt32): ClientBuilder

功能:配置客户端 HTTP/2 初始最大并发流数量。

参数:

返回值:

[h2]func maxFrameSize(UInt32)

public func maxFrameSize(size: UInt32): ClientBuilder

功能:配置客户端 HTTP/2 初始最大帧大小。

参数:

返回值:

[h2]func maxHeaderListSize(UInt32)

public func maxHeaderListSize(size: UInt32): ClientBuilder

功能:获取客户端支持的 HTTP/2 最大头部(Header)大小。这个大小指的是响应头部中所有头部字段(Header Field)的最大允许长度之和,其中包括所有字段名称(name)的长度、字段值(value)的长度以及每个字段自动添加的伪头开销(通常每个字段会有32字节的开销,这包括了HTTP/2协议本身为头部字段添加的伪头部信息)。默认情况下,这个最大长度被设置为 UInt32.Max。

参数:

返回值:

[h2]func noProxy()

public func noProxy(): ClientBuilder

功能:调用此函数后,客户端不使用任何代理。

返回值:

[h2]func poolSize(Int64)

public func poolSize(size: Int64): ClientBuilder

功能:配置 HTTP/1.1 客户端使用的连接池的大小,亦可表示对同一个主机(host:port)同时存在的连接数的最大值。

参数:

返回值:

异常:

[h2]func readTimeout(Duration)

public func readTimeout(timeout: Duration): ClientBuilder

功能:设定客户端读取一个响应的最大时长。

参数:

返回值:

[h2]func tlsConfig(TlsClientConfig)

public func tlsConfig(config: TlsClientConfig): ClientBuilder

功能:设置 TLS 层配置,默认不对其进行设置。

参数:

返回值:

[h2]func writeTimeout(Duration)

public func writeTimeout(timeout: Duration): ClientBuilder

功能:设定客户端发送一个请求的最大时长。

参数:

返回值:

[h2]prop cookieName

public prop cookieName: String

功能:获取 Cookie 对象的 cookie-name 值。

类型:String

[h2]prop cookieValue

public prop cookieValue: String

功能:获取 Cookie 对象的 cookie-value 值。

类型:String

[h2]prop domain

public prop domain: String

功能:获取 Cookie 对象的 domain-av 值。

类型:String

[h2]prop expires

public prop expires: ?DateTime

功能:获取 Cookie 对象的 expires-av 值。

类型:?DateTime

[h2]prop httpOnly

public prop httpOnly: Bool

功能:获取 Cookie 对象的 httpOnly-av 值。

类型:Bool

[h2]prop maxAge

public prop maxAge: ?Int64

功能:获取 Cookie 对象的 max-age-av 值。

类型:?Int64

[h2]prop others

public prop others: ArrayList<String>

功能:获取未被解析的属性。

类型:ArrayList<String>

[h2]prop path

public prop path: String

功能:获取 Cookie 对象的 path-av 值。

类型:String

[h2]prop secure

public prop secure: Bool

功能:获取 Cookie 对象的 secure-av 值。

类型:Bool

[h2]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)

功能:提供 Cookie 对象的公开构造器说明:该构造器会检查传入的各项属性是否满足协议要求,如果不满足则会产生 IllegalArgumentException。具体要求见 RFC 6265 4.1.1.。

Cookie 各属性中只有 cookie-name,cookie-value 是必需的,必须传入 name,value 参数,但 value 参数可以传入空字符串。

参数:

异常:

[h2]func toSetCookieString()

public func toSetCookieString(): String

功能:提供将 Cookie 转成字符串形式的函数,方便 server 设置 Set-Cookie header。

  • Cookie 各属性(包含 name,value)在对象创建时就被检查了,因此 toSetCookieString() 函数不会产生异常;
  • Cookie 必需的属性是 cookie-pair 即 cookie-name "=" cookie-value,cookie-value 可以为空字符串,toSetCookieString() 函数只会将设置过的属性写入字符串,即只有 "cookie-name=" 是必有的,其余部分是否存在取决于是否设置。

返回值:

class FileHandler

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

功能:用于处理文件下载或者文件上传。

文件下载:

文件上传:

[h2]init(String, FileHandlerType, Int64)

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

功能:FileHandler 的构造函数。

参数:

异常:

[h2]func handle(HttpContext)

public func handle(ctx: HttpContext): Unit

功能:根据请求对响应数据进行处理。

参数:

class FuncHandler

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

功能:HttpRequestHandler 接口包装类,把单个函数包装成 HttpRequestHandler。

[h2]FuncHandler((HttpContext) -> Unit)

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

功能:FuncHandler 的构造函数。

参数:

[h2]func handle(HttpContext)

public func handle(ctx: HttpContext): Unit

功能:处理 Http 请求。

参数:

class HttpContext

public class HttpContext

功能:Http 请求上下文,作为 HttpRequestHandler.handle 函数的参数在服务端使用。

[h2]prop clientCertificate

public prop clientCertificate: ?Array<X509Certificate>

功能:获取 Http 客户端证书。

类型:?Array<X509Certificate>

[h2]prop request

public prop request: HttpRequest

功能:获取 Http 请求。

类型:HttpRequest

[h2]prop responseBuilder

public prop responseBuilder: HttpResponseBuilder

功能:获取 Http 响应构建器。

类型:HttpResponseBuilder

class HttpHeaders

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

功能:此类用于表示 Http 报文中的 header 和 trailer,定义了相关增、删、改、查操作。

  • header 和 trailer 为键值映射集,由若干 field-line 组成,每一个 field-line 包含一个键 (field -name) 和若干值 (field-value)。
  • field-name 由 token 字符组成,不区分大小写,在该类中将转为小写保存。
  • field-value 由 vchar,SP 和 HTAB 组成,vchar 表示可见的 US-ASCII 字符,不得包含前后空格,不得为空值。
  • 详见 rfc 9110。

示例:

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

[h2]init()

public init()

功能:创建新的 HttpHeaders 实例。

[h2]func add(String, String)

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

功能:添加指定键值对。如果 name 已经存在,将在其对应的值列表中添加 value;如果 name 不存在,则添加 name 字段及其值 value。

参数:

异常:

[h2]func del(String)

public func del(name: String): Unit

功能:删除指定 name 对应的键值对。

参数:

[h2]func get(String)

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

功能:获取指定 name 对应的 value 值。

参数:

返回值:

[h2]func getFirst(String)

public func getFirst(name: String): ?String

功能:获取指定 name 对应的第一个 value 值。

参数:

返回值:

[h2]func isEmpty()

public func isEmpty(): Bool

功能:判断当前实例是否为空,即没有任何键值对。

返回值:

[h2]func iterator()

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

功能:获取迭代器,可用于遍历所有键值对。

返回值:

[h2]func set(String, String)

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

功能:设置指定键值对。如果 name 已经存在,传入的 value 将会覆盖之前的值。

参数:

异常:

class HttpRequest

public class HttpRequest <: ToString

功能:此类为 Http 请求类。

客户端发送请求时,需要构造一个 HttpRequest 实例,再编码成字节报文发出。

服务端处理请求时,需要把收到的请求解析成 HttpRequest 实例,并传给 handler 处理函数。

[h2]prop body

public prop body: InputStream

功能:获取 body。

  • body 不支持并发读取;
  • 默认 InputStream 实现类的 read 函数不支持多次读取。

类型:InputStream

[h2]prop bodySize

public prop bodySize: Option<Int64>

功能:获取请求 body 长度。

类型:Option<Int64>

[h2]prop close

public prop close: Bool

功能:表示该请求 header 是否包含 Connection: close。

类型:Bool

[h2]prop form

public prop form: Form

功能:获取请求中的表单信息。

  • 如果用该接口读取了 body,body 已被消费完,后续将无法通过 body.read 读取 body;
  • 如果 form 不符合 Form 格式,抛 UrlSyntaxException 异常。

类型:Form

[h2]prop headers

public prop headers: HttpHeaders

功能:获取 headers,headers 详述见 HttpHeaders 类,获取后,可通过调用 HttpHeaders 实例成员函数,修改该请求的 headers。

类型:HttpHeaders

[h2]prop method

public prop method: String

功能:获取 method,如 "GET", "POST",request 实例的 method 无法修改。

类型:String

[h2]prop readTimeout

public prop readTimeout: ?Duration

功能:表示该请求的请求级读超时时间。None 表示没有设置;Some(Duration) 表示设置了读超时时间。

类型:?Duration

[h2]prop remoteAddr

public prop remoteAddr: String

功能:用于服务端,获取对端地址,即客户端地址,格式为 ip: port,用户无法设置,自定义的 request 对象调用该属性返回 "",服务端 handler 中调用该属性返回客户端地址。

类型:String

[h2]prop trailers

public prop trailers: HttpHeaders

功能:获取 trailers,trailers 详述见 HttpHeaders 类,获取后,可通过调用 HttpHeaders 实例成员函数,修改该请求的 trailers。

类型:HttpHeaders

[h2]prop url

public prop url: URL

功能:获取 url,表示客户端访问的 url。

类型:URL

[h2]prop version

public prop version: Protocol

功能:获取 http 版本,如 HTTP1_1 和 HTTP2_0,request 实例的 version 无法修改。

类型:Protocol

[h2]prop writeTimeout

public prop writeTimeout: ?Duration

功能:表示该请求的请求级写超时时间,None 表示没有设置;Some(Duration) 表示设置了写超时时间。

类型:?Duration

[h2]func toString()

public override func toString(): String

功能:把请求转换为字符串,包括 start line,headers,body size,trailers。

例如:"GET /path HTTP/1.1\r\nhost: www.example.com\r\n\r\nbody size: 5\r\nbar: foo\r\n"。

返回值:

class HttpRequestBuilder

public class HttpRequestBuilder {
    public init()
}

功能:HttpRequestBuilder 类用于构造 HttpRequest 实例。

[h2]init()

public init()

功能:构造一个新 HttpRequestBuilder。

[h2]init(HttpRequest)

public init(request: HttpRequest)

功能: 通过 request 构造一个具有 request 属性的 HttpRequestBuilder。由于 body 成员是一个 InputStream,对原始的 request 的 body 的操作会影响到复制得到的 HttpRequest 的 body。HttpRequestBuilder 的 headers 和 trailers 是入参 request 的深拷贝。其余元素都是入参 request 的浅拷贝(因为是不可变对象,无需深拷贝)。

参数:

[h2]func addHeaders(HttpHeaders)

public func addHeaders(headers: HttpHeaders): HttpRequestBuilder

功能:向请求 header 添加参数 HttpHeaders 中的键值对。

参数:

返回值:

[h2]func addTrailers(HttpHeaders)

public func addTrailers(trailers: HttpHeaders): HttpRequestBuilder

功能:向请求 trailer 添加参数 HttpHeaders 中的键值对。

参数:

返回值:

[h2]func body(Array<UInt8>)

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

功能:设置请求 body。如果已经设置过,调用该函数将替换原 body。

参数:

返回值:

[h2]func body(InputStream)

public func body(body: InputStream): HttpRequestBuilder

功能:设置请求 body。如果已经设置过,调用该函数将替换原 body。

参数:

返回值:

[h2]func body(String)

public func body(body: String): HttpRequestBuilder

功能:设置请求 body,如果已经设置过,调用该函数将替换原 body调用该函数设置请求 body,则 body 将以内置的 InputStream 实现类表示,其大小已知。

参数:

返回值:

[h2]func build()

public func build(): HttpRequest

功能:根据 HttpRequestBuilder 实例生成一个 HttpRequest 实例。

返回值:

[h2]func connect()

public func connect(): HttpRequestBuilder

功能:构造 method 为 "CONNECT" 的请求的便捷函数。

返回值:

[h2]func delete()

public func delete(): HttpRequestBuilder

功能:构造 method 为 "DELETE" 的请求的便捷函数。

返回值:

[h2]func get()

public func get(): HttpRequestBuilder

功能:构造 method 为 "GET" 的请求的便捷函数。

返回值:

[h2]func head()

public func head(): HttpRequestBuilder

功能:构造 method 为 "HEAD" 的请求的便捷函数。

返回值:

[h2]func header(String, String)

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

功能:向请求 header 添加指定键值对,规则同 HttpHeaders 类的 add 函数。

参数:

返回值:

异常:

[h2]func method(String)

public func method(method: String): HttpRequestBuilder

功能:设置请求 method,默认请求 method 为 "GET"。

参数:

返回值:

异常:

[h2]func options()

public func options(): HttpRequestBuilder

功能:构造 method 为 "OPTIONS" 的请求的便捷函数。

返回值:

[h2]func post()

public func post(): HttpRequestBuilder

功能:构造 method 为 "POST" 的请求的便捷函数。

返回值:

[h2]func priority(Int64, Bool)

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

功能:设置 priority 头的便捷函数,调用此函数后,将生成 priority 头,形如:"priority: urgency=x, i"。如果通过设置请求头的函数设置了 priority 字段,调用此函数无效。如果多次调用此函数,以最后一次为准。

参数:

返回值:

[h2]func put()

public func put(): HttpRequestBuilder

功能:构造 method 为 "PUT" 的请求的便捷函数。

返回值:

[h2]func readTimeout(Duration)

public func readTimeout(timeout: Duration): HttpRequestBuilder

功能:设置此请求的读超时时间。如果传入的 Duration 为负,则会自动转为 0。如果用户设置了此读超时时间,那么该请求的读超时以此为准;如果用户没有设置,那么该请求的读超时以 Client 为准。

参数:

返回值:

[h2]func setHeaders(HttpHeaders)

public func setHeaders(headers: HttpHeaders): HttpRequestBuilder

功能:设置请求 header,如果已经设置过,调用该函数将替换原 header。

参数:

返回值:

[h2]func setTrailers(HttpHeaders)

public func setTrailers(trailers: HttpHeaders): HttpRequestBuilder

功能:设置请求 trailer,如果已经设置过,调用该函数将替换原 trailer。

参数:

返回值:

[h2]func trace()

public func trace(): HttpRequestBuilder

功能:构造 method 为 "TRACE" 的请求的便捷函数。

返回值:

[h2]func trailer(String, String)

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

功能:向请求 trailer 添加指定键值对,规则同 HttpHeaders 类的 add 函数。

参数:

返回值:

异常:

[h2]func url(String)

public func url(rawUrl: String): HttpRequestBuilder

功能:设置请求 url,默认 url 为空的 URL 对象。

参数:

返回值:

异常:

[h2]func url(URL)

public func url(url: URL): HttpRequestBuilder

功能:设置请求 url,默认 url 为空的 URL 对象,即 URL.parse("")。

参数:

返回值:

[h2]func version(Protocol)

public func version(version: Protocol): HttpRequestBuilder

功能:设置请求的 http 协议版本,默认为 UnknownProtocol(""),客户端会根据 tls 配置自动选择协议。

参数:

返回值:

[h2]func writeTimeout(Duration)

public func writeTimeout(timeout: Duration): HttpRequestBuilder

功能:设置此请求的写超时时间。如果传入的 Duration 为负,则会自动转为 0。如果用户设置了此写超时时间,那么该请求的写超时以此为准;如果用户没有设置,那么该请求的写超时以 Client 为准。

参数:

返回值:

class HttpResponse

public class HttpResponse <: ToString

功能:Http 响应类。

此类定义了 http 中响应 Response 的相关接口,客户端用该类读取服务端返回的响应。

[h2]prop body

public prop body: InputStream

功能:获取 body。

  • body 不支持并发读取;
  • 默认 InputStream 实现类的 read 函数不支持多次读取。

类型:InputStream

[h2]prop bodySize

public prop bodySize: Option<Int64>

功能:获取响应 body 长度。

类型:Option<Int64>

[h2]prop close

public prop close: Bool

功能:表示该响应 header 是否包含 Connection: close。

对于服务端,close 为 true 表示处理完该请求应该关闭连接;

对于客户端,close 为 true 表示如果收到响应后服务端未关闭连接,客户端应主动关闭连接。

类型:Bool

[h2]prop headers

public prop headers: HttpHeaders

功能:获取 headers,headers 详述见 HttpHeaders 类,获取后,可通过调用 HttpHeaders 实例成员函数,修改该请求的 headers。

类型:HttpHeaders

[h2]prop request

public prop request: Option<HttpRequest>

功能:获取该响应对应的请求,默认为 None。

类型:Option<HttpRequest>

[h2]prop status

public prop status: UInt16

功能:获取响应的状态码,默认值为 200。状态码由 100~599 的三位数字组成,状态码所反映的具体信息可参考 RFC 9110。

类型:UInt16

[h2]prop trailers

public prop trailers: HttpHeaders

功能:获取 trailers,trailers 详述见 HttpHeaders 类,获取后,可通过调用 HttpHeaders 实例成员函数,修改该请求的 trailers。

类型:HttpHeaders

[h2]prop version

public prop version: Protocol

功能:获取响应的协议版本,默认值为Http1_1。

类型:Protocol

[h2]func getPush()

public func getPush(): ?<ArrayList<HttpResponse>>

功能:获取服务器推送的响应,返回 None 代表未开启服务器推送功能,返回空 ArrayList 代表无服务器推送的响应。

返回值:

[h2]func toString()

public override func toString(): String

功能:把响应转换为字符串,包括 status-line,headers,body size, trailers。

例如:HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nbody size: 5\r\nbar: foo\r\n。

返回值:

class HttpResponseBuilder

public class HttpResponseBuilder {
    public init()
}

功能:用于构造 HttpResponse 实例。

[h2]init()

public init()

功能:构造一个新 HttpResponseBuilder。

[h2]func addHeaders(HttpHeaders)

public func addHeaders(headers: HttpHeaders): HttpResponseBuilder

功能:向响应 header 添加参数 HttpHeaders 中的键值对。

参数:

返回值:

[h2]func addTrailers(HttpHeaders)

public func addTrailers(trailers: HttpHeaders): HttpResponseBuilder

功能:向响应 trailer 添加参数 HttpHeaders 中的键值对。

参数:

返回值:

[h2]func body(Array<UInt8>)

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

功能:设置响应 body,如果已经设置过,调用该函数将替换原 body。

参数:

返回值:

[h2]func body(InputStream)

public func body(body: InputStream): HttpResponseBuilder

功能:设置响应 body,如果已经设置过,调用该函数将替换原 body调用该函数设置请求 body。

参数:

返回值:

[h2]func body(String)

public func body(body: String): HttpResponseBuilder

功能:设置响应 body,如果已经设置过,调用该函数将替换原 body调用该函数设置请求 body。

参数:

返回值:

[h2]func build()

public func build(): HttpResponse

功能:根据 HttpResponseBuilder 实例生成一个 HttpResponse 实例。

返回值:

[h2]func header(String, String)

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

功能:向响应 header 添加指定键值对,规则同 HttpHeaders 类的 add 函数。

参数:

返回值:

异常:

[h2]func request(HttpRequest)

public func request(request: HttpRequest): HttpResponseBuilder

功能:设置响应对应的请求。

参数:

返回值:

[h2]func setHeaders(HttpHeaders)

public func setHeaders(headers: HttpHeaders): HttpResponseBuilder

功能:设置响应 header,如果已经设置过,调用该函数将替换原 header。

参数:

返回值:

[h2]func setTrailers(HttpHeaders)

public func setTrailers(trailers: HttpHeaders): HttpResponseBuilder

功能:设置响应 trailer,如果已经设置过,调用该函数将替换原 trailer。

参数:

返回值:

[h2]func status(UInt16)

public func status(status: UInt16): HttpResponseBuilder

功能:设置 http 响应状态码。

参数:

返回值:

异常:

[h2]func trailer(String, String)

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

功能:向响应 trailer 添加指定键值对,规则同 HttpHeaders 类的 add 函数。

参数:

返回值:

异常:

[h2]func version(Protocol)

public func version(version: Protocol): HttpResponseBuilder

功能:设置 http 响应协议版本。

参数:

返回值:

class HttpResponsePusher

public class HttpResponsePusher

功能:HTTP/2 服务器推送。

如果服务器收到请求后,认为客户端后续还需要某些关联资源,可以将其提前推送到客户端;

服务端推送包括推送请求和推送响应;

启用服务端推送需要先调用 push 函数发送推送请求,并向服务器注册该请求对应的 handler,用以生成推送响应;

客户端可设置拒绝服务端推送;

不允许嵌套推送,即不允许在推送请求对应的 handler 中再次推送。嵌套推送情况下,服务端将不执行推送,并打印日志进行提示。

[h2]static func getPusher(HttpContext)

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

功能:获取 HttpResponsePusher 实例,如果客户端拒绝推送,将返回 None。

参数:

返回值:

[h2]func push(String, String, HttpHeaders)

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

功能:向客户端发送推送请求,path 为请求地址,method 为请求方法,header 为请求头。

参数:

class HttpResponseWriter

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

功能:HTTP response 消息体 Writer,支持用户控制消息体的发送过程。

第一次调用 write 函数时,将立即发送 header 和通过参数传入的 body,此后每次调用 write,发送通过参数传入的 body。

对于 HTTP/1.1,如果设置了 transfer-encoding: chunked,用户每调用一次 write,将发送一个 chunk。

对于 HTTP/2,用户每调用一次 write,将把指定数据封装并发出。

[h2]HttpResponseWriter(HttpContext)

public HttpResponseWriter(let ctx: HttpContext)

功能:构造一个 HttpResponseWriter 实例。

参数:

[h2]func write(Array<Byte>)

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

功能:发送 buf 中数据到客户端。

参数:

异常:

class NotFoundHandler

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

功能:便捷的 Http 请求处理器,404 Not Found 处理器。

[h2]init()

public init()

功能:构造一个 NotFoundHandler 对象。

[h2]func handle(HttpContext)

public func handle(ctx: HttpContext): Unit

功能:处理 Http 请求,回复 404 响应。

参数:

class OptionsHandler

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

功能:便捷的 Http 处理器,用于处理 OPTIONS 请求。固定返回 "Allow: OPTIONS,GET,HEAD,POST,PUT,DELETE" 响应头。

[h2]init()

public init()

功能:构造一个 NotFoundHandler 对象。

[h2]func handle(HttpContext)

public func handle(ctx: HttpContext): Unit

功能:处理 Http OPTIONS 请求。

参数:

class ProtocolService

public abstract class ProtocolService

功能:Http 协议服务实例,为单个客户端连接提供 Http 服务,包括对客户端 request 报文的解析、 request 的分发处理、 response 的发送等。

[h2]prop server

open protected mut prop server: Server

功能:返回 Server 实例,提供默认实现,设置为绑定的 Server 实例

[h2]func serve

protected func serve(): Unit

功能:处理来自客户端连接的请求,不提供默认实现。

[h2]func closeGracefully

open protected func closeGracefully(): Unit

功能:优雅关闭连接,提供默认实现,无任何行为。

[h2]func close

open protected func close(): Unit

功能:强制关闭连接,提供默认实现,无任何行为。

class RedirectHandler

public class RedirectHandler <: HttpRequestHandler

功能:便捷的 Http 处理器,用于回复重定向响应。

[h2]init(String, UInt16)

public init(url: String, code: UInt16)

功能:RedirectHandler 的构造函数。

参数:

异常:

[h2]func handle(HttpContext)

public func handle(ctx: HttpContext): Unit

功能:处理 Http 请求,回复重定向响应。

参数:

class Server

public class Server

功能:提供 HTTP 服务的 Server 类。

  • 启动服务,在指定地址及端口等待用户连接、服务用户的 http request;
  • 关闭服务,包括关闭所有已有连接;
  • 提供注册处理 http request 的 handler 的机制,根据注册信息分发 request 到相应的 handler;
  • 提供 tls 证书热机制;
  • 提供 shutdown 回调机制;
  • 通过 Logger.level 开启、关闭日志打印,包括按照用户要求打印相应级别的日志;
  • Server 文档中未明确说明支持版本的配置,在 HTTP/1.1 与 HTTP/2 都会生效。

[h2]prop addr

public prop addr: String

功能:获取服务端监听地址,格式为 IP 或者 域名。

类型:String

[h2]prop distributor

public prop distributor: HttpRequestDistributor

功能:获取请求分发器,请求分发器会根据 url 将请求分发给对应的 handler。

类型:HttpRequestDistributor

[h2]prop enableConnectProtocol

public prop enableConnectProtocol: Bool

功能:HTTP/2 专用,用来限制对端发送的报文是否支持通过 connect 方法升级协议,true 表示支持。

类型:Bool

[h2]prop headerTableSize

public prop headerTableSize: UInt32

功能:获取服务端 HTTP/2 Hpack 动态表的初始值,默认值为 4096。

类型:UInt32

[h2]prop httpKeepAliveTimeout

public prop httpKeepAliveTimeout: Duration

功能:HTTP/1.1 专用,获取服务器设定的保持长连接的超时时间。

类型:Duration

[h2]prop initialWindowSize

public prop initialWindowSize: UInt32

功能:HTTP/2 专用,用来限制对端发送的报文stream 初始流量窗口大小。默认值为 65535 ,取值范围为 0 至 2^31 - 1。

类型:UInt32

[h2]prop listener

public prop listener: ServerSocket

功能:获取服务器绑定 socket。

类型:ServerSocket

[h2]prop logger

public prop logger: Logger

功能:获取服务器日志记录器,设置 logger.level 将立即生效,记录器应该是线程安全的。

类型:Logger

[h2]prop maxConcurrentStreams

public prop maxConcurrentStreams: UInt32

功能:HTTP/2 专用,用来限制连接同时处理的最大请求数量。

类型:UInt32

[h2]prop maxFrameSize

public prop maxFrameSize: UInt32

功能:HTTP/2 专用,用来限制对端发送的报文一个帧的最大长度。默认值为 16384. 取值范围为 2^14 至 2^24 - 1。

类型:UInt32

[h2]prop maxHeaderListSize

public prop maxHeaderListSize: UInt32

功能:获取客户端支持的 HTTP/2 最大头部(Header)大小。这个大小指的是响应头部中所有头部字段(Header Field)的最大允许长度之和,其中包括所有字段名称(name)的长度、字段值(value)的长度以及每个字段自动添加的伪头开销(通常每个字段会有32字节的开销,这包括了HTTP/2协议本身为头部字段添加的伪头部信息)。默认情况下,这个最大长度被设置为 UInt32.Max。

类型:UInt32

[h2]prop maxRequestBodySize

public prop maxRequestBodySize: Int64

功能:获取服务器设定的读取请求的请求体最大值,仅对于 HTTP/1.1 且未设置 "Transfer-Encoding: chunked" 的请求生效。

类型:Int64

[h2]prop maxRequestHeaderSize

public prop maxRequestHeaderSize: Int64

功能:获取服务器设定的读取请求的请求头最大值。仅对 HTTP/1.1 生效,HTTP/2 中有专门的配置 maxHeaderListSize。

类型:Int64

[h2]prop port

public prop port: UInt16

功能:获取服务端监听端口。

类型:UInt16

[h2]prop protocolServiceFactory

public prop protocolServiceFactory: ProtocolServiceFactory

功能:获取协议服务工厂,服务协议工厂会生成每个协议所需的服务实例。

类型:ProtocolServiceFactory

[h2]prop readHeaderTimeout

public prop readHeaderTimeout: Duration

功能:获取服务器设定的读取请求头的超时时间。

类型:Duration

[h2]prop readTimeout

public prop readTimeout: Duration

功能:获取服务器设定的读取整个请求的超时时间。

类型:Duration

[h2]prop servicePoolConfig

public prop servicePoolConfig: ServicePoolConfig

功能:获取协程池配置实例。

类型:ServicePoolConfig

[h2]prop transportConfig

public prop transportConfig: TransportConfig

功能:获取服务器设定的传输层配置。

类型:TransportConfig

[h2]prop writeTimeout

public prop writeTimeout: Duration

功能:获取服务器设定的写响应的超时时间。

类型:Duration

[h2]func afterBind(()->Unit)

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

功能:注册服务器启动时的回调函数,服务内部 ServerSocket 实例 bind 之后,accept 之前将调用该函数。重复调用将覆盖之前注册的函数。

参数:

[h2]func close()

public func close(): Unit

功能:关闭服务器,服务器关闭后将不再对请求进行读取与处理,重复关闭将只有第一次生效(包括 close 和 closeGracefully)。

[h2]func closeGracefully()

public func closeGracefully(): Unit

功能:关闭服务器,服务器关闭后将不再对请求进行读取,当前正在进行处理的服务器待处理结束后进行关闭。

[h2]func getTlsConfig()

public func getTlsConfig(): ?TlsServerConfig

功能:获取服务器设定的 TLS 层配置。

返回值:

[h2]func onShutdown(()->Unit)

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

功能:注册服务器关闭时的回调函数,服务器关闭时将调用该回调函数,重复调用将覆盖之前注册的函数。

参数:

[h2]func serve()

public func serve(): Unit

功能:启动服务端进程,不支持重复启动。

h1 request 检查和处理:

h1 response 检查和处理:

启用 h2 服务:tlsConfig 中 supportedAlpnProtocols 需包含 "h2",此后如果 tls 层 alpn 协商结果为 h2,则启用 h2 服务。

h2 request 检查和处理:

h2 response 检查和处理:

h2 server 发完 response 之后,如果 stream 状态不是 CLOSED,会发送带 NO_ERROR 错误码的 RST 帧关闭 stream,避免已经处理完毕的 stream 继续占用服务器资源。

h2 流量控制:

h2 请求优先级:

默认 ProtocolServiceFactory 协议选择:

异常:

[h2]func updateCA(Array<X509Certificate>)

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

功能:对 CA 证书进行热更新。

参数:

异常:

[h2]func updateCA(String)

public func updateCA(newCaFile: String): Unit

功能:对 CA 证书进行热更新。

参数:

异常:

[h2]func updateCert(Array<X509Certificate>, PrivateKey)

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

功能:对 TLS 证书进行热更新。

参数:

异常:

[h2]func updateCert(String, String)

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

功能:对 TLS 证书进行热更新。

参数:

异常:

class ServerBuilder

public class ServerBuilder {
    public init()
}

功能:提供 Server 实例构建器。

支持通过如下参数构造一个 Http Server:

除地址端口、shutdown 回调外,均提供默认实现,用户在构造 server 过程中可不指定其他构建参数。

ServerBuilder 文档中未明确说明支持版本的配置,在 HTTP/1.1 与 HTTP/2 都会生效。

[h2]init()

public init()

功能:创建 ServerBuilder 实例。

[h2]func addr(String)

public func addr(addr: String): ServerBuilder

功能:设置服务端监听地址,若 listener 被设定,此值被忽略。

参数:

返回值:

[h2]func afterBind(()->Unit)

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

功能:注册服务器启动时的回调函数,服务内部 ServerSocket 实例 bind 之后,accept 之前将调用该函数。重复调用将覆盖之前注册的函数。

参数:

返回值:

[h2]func build()

public func build(): Server

功能:根据设置的属性构建 Server 实例。

返回值:

异常:

[h2]func distributor(HttpRequestDistributor)

public func distributor(distributor: HttpRequestDistributor): ServerBuilder

功能:设置请求分发器,请求分发器会根据 url 将请求分发给对应的 handler。不设置时使用默认请求分发器。

参数:

返回值:

[h2]func enableConnectProtocol(Bool)

public func enableConnectProtocol(flag: Bool): ServerBuilder

功能:HTTP/2 专用,设置本端是否接收 CONNECT 请求,默认 false。

参数:

返回值:

[h2]func headerTableSize(UInt32)

public func headerTableSize(size: UInt32): ServerBuilder

功能:设置服务端 HTTP/2 Hpack 动态表的初始值,默认值为 4096。

参数:

返回值:

[h2]func httpKeepAliveTimeout(Duration)

public func httpKeepAliveTimeout(timeout: Duration): ServerBuilder

功能:HTTP/1.1 专用,设定服务端连接保活时长,该时长内客户端未再次发送请求,服务端将关闭长连接,默认不进行限制。

参数:

返回值:

[h2]func initialWindowSize(UInt32)

public func initialWindowSize(size: UInt32): ServerBuilder

功能:HTTP/2 专用,设置当前服务器上每个流的接收报文的初始流量窗口大小,默认值为 65535。取值范围为 0 至 2^31 - 1。

参数:

返回值:

[h2]func listener(ServerSocket)

public func listener(listener: ServerSocket): ServerBuilder

功能:服务端调用此函数对指定 socket 进行绑定监听。

参数:

返回值:

[h2]func logger(Logger)

public func logger(logger: Logger): ServerBuilder

功能:设定服务器的 logger,默认 logger 级别为 INFO,logger 内容将写入 Console.stdout。

参数:

返回值:

[h2]func maxConcurrentStreams(UInt32)

public func maxConcurrentStreams(size: UInt32): ServerBuilder

功能:HTTP/2 专用,设置本端同时处理的最大请求数量,限制对端并发发送请求的数量,默认值为 100。

参数:

返回值:

[h2]func maxFrameSize(UInt32)

public func maxFrameSize(size: UInt32): ServerBuilder

功能:HTTP/2 专用,设置本端接收的一个帧的最大长度,用来限制对端发送帧的长度,默认值为 16384. 取值范围为 2^14 至 2^24 - 1。

参数:

返回值:

[h2]func maxHeaderListSize(UInt32)

public func maxHeaderListSize(size: UInt32): ServerBuilder

功能:获取客户端支持的 HTTP/2 最大头部(Header)大小。这个大小指的是响应头部中所有头部字段(Header Field)的最大允许长度之和,其中包括所有字段名称(name)的长度、字段值(value)的长度以及每个字段自动添加的伪头开销(通常每个字段会有32字节的开销,这包括了HTTP/2协议本身为头部字段添加的伪头部信息)。默认情况下,这个最大长度被设置为 UInt32.Max。

参数:

返回值:

[h2]func maxRequestBodySize(Int64)

public func maxRequestBodySize(size: Int64): ServerBuilder

功能:设置服务端允许客户端发送单个请求的请求体最大长度,请求体长度超过该值时,将返回状态码为 413 的响应。默认值为 2M。仅对于 HTTP/1.1 且未设置 "Transfer-Encoding: chunked" 的请求生效。

参数:

返回值:

异常:

[h2]func maxRequestHeaderSize(Int64)

public func maxRequestHeaderSize(size: Int64): ServerBuilder

功能:设定服务端允许客户端发送单个请求的请求头最大长度,请求头长度超过该值时,将返回状态码为 431 的响应;仅对 HTTP/1.1 生效,HTTP/2 中有专门的配置 maxHeaderListSize。

参数:

返回值:

异常:

[h2]func onShutdown(()->Unit)

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

功能:注册服务器关闭时的回调函数,服务器关闭时将调用该回调函数,重复调用将覆盖之前注册的函数。

参数:

返回值:

[h2]func port(UInt16)

public func port(port: UInt16): ServerBuilder

功能:设置服务端监听端口,若 listener 被设定,此值被忽略。

参数:

返回值:

[h2]func protocolServiceFactory(ProtocolServiceFactory)

public func protocolServiceFactory(factory: ProtocolServiceFactory): ServerBuilder

功能:设置协议服务工厂,服务协议工厂会生成每个协议所需的服务实例,不设置时使用默认工厂。

参数:

返回值:

[h2]func readHeaderTimeout(Duration)

public func readHeaderTimeout(timeout: Duration): ServerBuilder

功能:设定服务端读取客户端发送一个请求的请求头最大时长,超过该时长将不再进行读取并关闭连接,默认不进行限制。

参数:

返回值:

[h2]func readTimeout(Duration)

public func readTimeout(timeout: Duration): ServerBuilder

功能:设定服务端读取一个请求的最大时长,超过该时长将不再进行读取并关闭连接,默认不进行限制。

参数:

返回值:

[h2]func servicePoolConfig(ServicePoolConfig)

public func servicePoolConfig(cfg: ServicePoolConfig): ServerBuilder

功能:服务过程中使用的协程池相关设置,具体说明见 ServicePoolConfig 结构体。

参数:

返回值:

[h2]func tlsConfig(TlsServerConfig)

public func tlsConfig(config: TlsServerConfig): ServerBuilder

功能:设置 TLS 层配置,默认不对其进行设置。

参数:

返回值:

[h2]func transportConfig(TransportConfig)

public func transportConfig(config: TransportConfig): ServerBuilder

功能:设置传输层配置,默认配置详见 TransportConfig 结构体说明。

参数:

返回值:

[h2]func writeTimeout(Duration)

public func writeTimeout(timeout: Duration): ServerBuilder

功能:设定服务端发送一个响应的最大时长,超过该时长将不再进行写入并关闭连接,默认不进行限制。

参数:

返回值:

class WebSocket

public class WebSocket

功能:提供 WebSocket 服务的相关类,提供 WebSocket 连接的读、写、关闭等函数。用户通过 upgradeFrom 函数以获取 WebSocket 连接。

详细说明见下文接口说明,接口行为以 RFC 6455 为准。

[h2]prop logger

public prop logger: Logger

功能:日志记录器。

类型:Logger

[h2]prop subProtocol

public prop subProtocol: String

功能:获取与对端协商到的 subProtocol,协商时,客户端提供一个按偏好排名的 subProtocols 列表,服务器从中选取一个或零个子协议。

类型:String

[h2]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)

功能:提供客户端升级到 WebSocket 协议的函数。

客户端的升级流程为:传入 client 对象,url 对象,构建升级请求,请求服务器后验证其响应,如果握手成功,则返回 WebSocket 对象用于 WebSocket 通讯,并返回 101 响应头的 HttpHeaders 对象给用户。暂不支持 extensions如果子协议协商成功,用户可通过调用返回的 WebSocket 的 subProtocol 查看子协议。

参数:

返回值:

异常:

[h2]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

功能:提供服务端升级到 WebSocket 协议的函数,通常在 handler 中使用。

服务端升级的流程为:收到客户端发来的升级请求,验证请求,如果验证通过,则回复 101 响应并返回 WebSocket 对象用于 WebSocket 通讯。

参数:

返回值:

[h2]func closeConn()

public func closeConn(): Unit

功能:提供关闭底层 WebSocket 连接的函数。

直接关闭底层连接。正常的关闭流程需要遵循协议规定的握手流程,即先发送 Close 帧给对端,并等待对端回应的 Close 帧。握手流程结束后方可关闭底层连接。

[h2]func read()

public func read(): WebSocketFrame

功能:从连接中读取一个帧,如果连接上数据未就绪会阻塞,非线程安全(即对同一个 WebSocket 对象不支持多线程读)。

read 函数返回一个 WebSocketFrame 对象,用户可以调用 WebSocketFrame 的 frameType,fin 属性确定其帧类型和是否是分段帧调用。通过 WebSocketFrame 的 payload 函数得到原始二进制数据数组:Array<UInt8>

  • 数据帧(Text,Binary)可以分段,用户需要多次调用 read 将所有分段帧读完(以下称为接收到完整的 message),再将分段帧的 payload 按接收序拼接Text 帧的 payload 为 UTF-8 编码,用户在接收到完整的 message 后,调用 String.fromUtf8函数将拼接后的 payload 转成字符串Binary 帧的 payload 的意义由使用其的应用确定,用户在接收到完整的 message 后,将拼接后的 payload 传给上层应用;
  • 控制帧(Close,Ping,Pong)不可分段;
  • 控制帧本身不可分段,但其可以穿插在分段的数据帧之间。分段的数据帧之间不可出现其他数据帧,如果用户收到穿插的分段数据帧,则需要当作错误处理;
  • 客户端收到 masked 帧,服务器收到 unmasked 帧,断开底层连接并抛出异常;
  • rsv1、rsv2、rsv3 位被设置(暂不支持 extensions,因此 rsv 位必须为 0),断开底层连接并抛出异常;
  • 收到无法理解的帧类型(只支持 Continuation,Text,Binary,Close,Ping,Pong),断开底层连接并抛出异常;
  • 收到分段或 payload 长度大于 125 bytes 的控制帧(Close,Ping,Pong),断开底层连接并抛出异常;
  • 收到 payload 长度大于 20M 的帧,断开底层连接并抛出异常;
  • closeConn 关闭连接后继续调用读,抛出异常。

返回值:

异常:

[h2]func write(WebSocketFrameType, Array<UInt8>, Int64)

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

功能:发送数据,非线程安全(即对同一个 WebSocket 对象不支持多线程写)。

write 函数将数据以 WebSocket 帧的形式发送给对端;

  • 如果发送数据帧(Text,Binary),传入的 byteArray 如果大于 frameSize (默认 4 * 1024 bytes),我们会将其分成小于等于 frameSize 的 payload 以分段帧的形式发送,否则不分段;
  • 如果发送控制帧(Close,Ping,Pong),传入的 byteArray 的大小需要小于等于 125 bytes,Close 帧的前两个字节为状态码,可用的状态码见 RFC 6455 7.4. Status Codes协议规定,Close 帧发送之后,禁止再发送数据帧,如果发送则会抛出异常;
  • 用户需要自己保证其传入的 byteArray 符合协议,如 Text 帧的 payload 需要是 UTF-8 编码,如果数据帧设置了 frameSize,那么需要大于 0,否则抛出异常;
  • 发送数据帧时,frameSize 小于等于 0,抛出异常;
  • 用户发送控制帧时,传入的数据大于 125 bytes,抛出异常;
  • 用户传入非 Text,Binary,Close,Ping,Pong 类型的帧类型,抛出异常;
  • 发送 Close 帧时传入非法的状态码,或 reason 数据超过 123 bytes,抛出异常;
  • 发送完 Close 帧后继续发送数据帧,抛出异常;
  • closeConn 关闭连接后调用写,抛出异常。

参数:

异常:

[h2]func writeCloseFrame(?UInt16, String)

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

功能:发送 Close 帧。

协议规定,Close 帧发送之后,禁止再发送数据帧。如果用户不设置 status,那么 reason 不会被发送(即有 reason 必有 status);控制帧的 payload 不超过 125 bytes,Close 帧的前两个 bytes 为 status,因此 reason 不能超过 123 bytes,closeConn 关闭连接后调用写,抛出异常。

参数:

异常:

[h2]func writePingFrame(Array<UInt8>)

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

功能:提供发送 Ping 帧的快捷函数,closeConn 关闭连接后调用写,抛出异常。

参数:

异常:

[h2]func writePongFrame(Array<UInt8>)

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

功能:提供发送 Pong 帧的快捷函数,closeConn 关闭连接后调用写,抛出异常。

参数:

异常:

class WebSocketFrame

public class WebSocketFrame

功能:WebSocket 用于读的基本单元。

WebSocketFrame 提供了三个属性,其中 fin 和 frameType 共同说明了帧是否分段和帧的类型。payload 为帧的载荷。

由于控制帧可以穿插在分段帧之间,用户在拼接分段帧的 payload 时需要单独处理控制帧。分段帧之间仅可穿插控制帧,如果用户在分段帧之间接收到其他数据帧,则需要当作错误处理。

[h2]prop fin

public prop fin: Bool

功能:获取 WebSocketFrame 的 fin 属性,fin 与 frameType 共同说明了帧是否分段和帧的类型。

类型:Bool

[h2]prop frameType

public prop frameType: WebSocketFrameType

功能:获取 WebSocketFrame 的帧类型,fin 与 frameType 共同说明了帧是否分段和帧的类型。

类型:WebSocketFrameType

[h2]prop payload

public prop payload: Array<UInt8>

功能:获取 WebSocketFrame 的帧载荷。如果是分段数据帧,用户需要在接收到完整的 message 后,将所有分段的 payload 按接收序拼接。

类型:Array<UInt8>