k6/websockets
Thek6/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
The WebSocket server URL (must start with
ws:// or wss://)Optional subprotocol(s) to use
Properties
Type of binary data being received. Can be
"blob" or "arraybuffer" (default: "blob")Number of bytes queued to be sent (read-only)
Extensions selected by the server (read-only)
Subprotocol selected by the server (read-only)
Current connection state:
0(CONNECTING): Connection not yet established1(OPEN): Connection is open and ready to communicate2(CLOSING): Connection is in the process of closing3(CLOSED): Connection is closed
The WebSocket URL (read-only)
Methods
send()
Sends data through the WebSocket connection.Data to send to the server
close()
Closes the WebSocket connection.Numeric status code (default: 1000)
Human-readable closing reason
Event Handlers
addEventListener()
Registers an event listener for WebSocket events.Event type:
"open", "message", "close", "error", or "ping"/"pong"Function to call when the event occurs
Complete Example
Based on the k6 source example:Event Objects
MessageEvent
The data sent by the server
The origin of the WebSocket server
CloseEvent
The close code sent by the server
The reason for closing
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