WebSocket Deflate extension

Ktor implements Deflate WebSocket extensions RFC-7692 for the client and server. The extension can transparently compress frame before sending, and decompress after receiving. It’s useful to enable this extension if you’re sending large amounts of text data.

The API is production ready, but may be slightly modified in a minor release. This is why it’s marked with the @ExperimentalWebSocketExtensionsApi annotation. If you want to use this API you need to OptIn:

  1. @OptIn(ExperimentalWebSocketExtensionsApi::class)

If you want to leave your feedback or subscribe on updates, check KTOR-688 design issue.

Installation

To use the extension it should be installed first. To do that we can use install method in extensions block:

  1. // For client and server
  2. install(WebSockets) {
  3. extensions {
  4. install(WebSocketDeflateExtension) {
  5. /**
  6. * Compression level to use for [java.util.zip.Deflater].
  7. */
  8. compressionLevel = Deflater.DEFAULT_COMPRESSION
  9. /**
  10. * Prevent to compress small outgoing frames.
  11. */
  12. compressIfBiggerThan(bytes = 4 * 1024)
  13. }
  14. }
  15. }

Advanced configuration parameters

Context takeover

Specify if the client (and server) should use compression window. Enabling these parameters reduce the amount of space allocated per single session. Please note that window size cannot be configured due to limitations of java.util.zip.Deflater API. The value is fixed to 15.

  1. clientNoContextTakeOver = false
  2. serverNoContextTakeOver = false

These parameters are described in RFC-7692 Section 7.1.1

Specify compress condition

To specify a compress condition explicitly, you can use the compressIf method. For instance, to compress text-only:

  1. compressIf { frame ->
  2. frame is Frame.Text
  3. }

All calls to compressIf will be evaluated before compression takes place.

Fine-tune list of protocols

The list of protocols to send can be edited as needed using the configureProtocols method:

  1. configureProtocols { protocols ->
  2. protocols.clear()
  3. protocols.add(...)
  4. }