Skip to main content

k6/websockets

The k6/websockets module provides a modern, standards-compliant WebSocket API for k6. This is the newer WebSocket implementation that follows the browser WebSocket API more closely.
This module is different from k6/ws, which provides the legacy WebSocket API. The k6/websockets module offers a more modern, event-driven approach.

WebSocket Class

The main class for creating WebSocket connections.

Constructor

string
required
The WebSocket server URL (must start with ws:// or wss://)
string | string[]
Optional subprotocol(s) to use

Properties

string
Type of binary data being received. Can be "blob" or "arraybuffer" (default: "blob")
number
Number of bytes queued to be sent (read-only)
string
Extensions selected by the server (read-only)
string
Subprotocol selected by the server (read-only)
number
Current connection state:
  • 0 (CONNECTING): Connection not yet established
  • 1 (OPEN): Connection is open and ready to communicate
  • 2 (CLOSING): Connection is in the process of closing
  • 3 (CLOSED): Connection is closed
string
The WebSocket URL (read-only)

Methods

send()

Sends data through the WebSocket connection.
string | ArrayBuffer | Blob
required
Data to send to the server

close()

Closes the WebSocket connection.
number
Numeric status code (default: 1000)
string
Human-readable closing reason

Event Handlers

addEventListener()

Registers an event listener for WebSocket events.
string
required
Event type: "open", "message", "close", "error", or "ping"/"pong"
function
required
Function to call when the event occurs

Complete Example

Based on the k6 source example:

Event Objects

MessageEvent

string | ArrayBuffer | Blob
The data sent by the server
string
The origin of the WebSocket server

CloseEvent

number
The close code sent by the server
string
The reason for closing
boolean
Whether the connection closed cleanly

Key Differences from k6/ws

k6/websockets

  • Event-driven API
  • Multiple event listeners
  • Standards-compliant
  • Modern browser-like API

k6/ws

  • Callback-based API
  • Single handler per event
  • Legacy implementation
  • Simpler for basic use cases

Use Cases

  • Real-time chat applications
  • Live notifications and updates
  • Multiplayer games
  • Financial tickers and dashboards
  • IoT device communication