k6/websockets module implements the browser WebSocket API with additional k6-specific functionality like cookies, tags, and custom headers.
The
k6/experimental/websockets module has been deprecated. Use k6/websockets instead.Overview
This module uses a global event loop instead of a local one, which enables a single VU to handle multiple concurrent WebSocket connections. This improves performance compared to the olderk6/ws module.
Key Difference from k6/ws
The main difference betweenk6/websockets and k6/ws is that this module uses a global event loop, allowing a single VU to have multiple concurrent connections, which improves performance.
Importing the Module
API Reference
Classes and Methods
Instance Methods
Closes the WebSocket connection.
Sends a ping frame to the server.
Sends data through the WebSocket connection.Parameters:
Data to send to the server
Instance Properties
The current state of the connection. One of:
0- CONNECTING1- OPEN2- CLOSING3- CLOSED
The URL of the connection as resolved by the constructor.
The number of bytes queued using
send() but not yet transmitted.Controls the type of binary data received. Either
"blob" (default) or "arraybuffer".Event Handlers
Handler called when the connection is established.
Handler called when a message is received.
Handler called when an error occurs.
Handler called when the connection is closed.
Handler called when a ping is received.
Handler called when a pong is received.
Connection Parameters
Params Object
Compression algorithm to use. Currently only
"deflate" is supported.Cookie jar for the WebSocket connection. Uses the default VU cookie jar if not specified.
Custom HTTP headers to include in the WebSocket handshake request.
Custom metric tags for filtering results and setting thresholds.
WebSocket Metrics
k6 automatically collects WebSocket-specific metrics:| Metric | Type | Description |
|---|---|---|
ws_connecting | Trend | Time to establish connection |
ws_session_duration | Trend | Total session duration |
ws_sessions | Counter | Total number of sessions |
ws_msgs_sent | Counter | Messages sent |
ws_msgs_received | Counter | Messages received |
ws_ping | Trend | Ping round-trip time |
Examples
Multiple Concurrent Connections
This example shows how a single VU can run multiple WebSocket connections asynchronously:Related Resources
k6/ws
Alternative WebSocket module with local event loop
Blob
Handle binary data in WebSocket messages
WebSocket Testing Guide
Learn WebSocket testing patterns
Metrics Reference
WebSocket metrics documentation