Escribe para buscar…

WebSocket

WebSocket is a protocol that provides a full-duplex communication session between the user's browser and a server over a single TCP connection. It is particularly useful for creating applications that require real-time data transfer from and to the server.

Esta página todavía no se ha traducido — se muestra en su idioma original:English

Introduction

WebSockets shine in scenarios that require real-time communication. For example, they are widely used in chat applications, online multiplayer games, and real-time data dashboards.

For a mobile application, WebSockets enable seamless interaction with a backend server, allowing mobile clients to maintain a live link to the server for push notifications or updates. In mobile development, WebSockets are useful for building apps where timely delivery of message updates is critical, such as collaborative editing tools or live sports score apps.

If you are new to WebSockets, we recommend reading our WebSocket overview first.

Server

To use WebSockets, you need to include the ktor-server-websockets dependency:

yaml
dependencies:
  - $ktor.server.websockets

Install the WebSockets plugin by passing it to the install function within your application module:

kotlin
import io.ktor.server.application.*
import io.ktor.server.websocket.*
// ...
fun Application.module() {
    install(WebSockets)
    // ...
}

Configure WebSockets

You can customize the plugin’s behavior within the install block using WebSocketOptions:

  • pingPeriod: Frequency of keep-alive pings.
  • timeout: Duration after which an inactive connection is closed.
  • maxFrameSize: Maximum size allowed for a single frame.
  • masking: Whether to enable frame masking.
  • contentConverter: A converter for automated serialization and deserialization.
kotlin
install(WebSockets) {
    pingPeriod = 15.seconds
    timeout = 15.seconds
    maxFrameSize = Long.MAX_VALUE
    masking = false
}

Handle WebSockets sessions

Define a WebSocket endpoint by calling the webSocket function inside your routing block:

kotlin
routing {
    webSocket("/echo") {
       // Handle a WebSocket session
    }
}

Estás leyendo una vista previa.

Inicia sesión para leer el artículo completo. Cualquier cuenta abre 4 artículos gratuitos al mes; el alumnado y el profesorado leen las páginas de su curso sin límite.

Iniciar sesión