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
constructor
Instance Methods
function
Closes the WebSocket connection.
function
Sends a ping frame to the server.
function
Sends data through the WebSocket connection.Parameters:
string | ArrayBuffer | Blob
required
Data to send to the server
function
Instance Properties
number
The current state of the connection. One of:
0- CONNECTING1- OPEN2- CLOSING3- CLOSED
string
The URL of the connection as resolved by the constructor.
number
The number of bytes queued using
send() but not yet transmitted.string
Controls the type of binary data received. Either
"blob" (default) or "arraybuffer".Event Handlers
function
Handler called when the connection is established.
function
Handler called when a message is received.
function
Handler called when an error occurs.
function
Handler called when the connection is closed.
function
Handler called when a ping is received.
function
Handler called when a pong is received.
Connection Parameters
Params Object
string
Compression algorithm to use. Currently only
"deflate" is supported.http.CookieJar
Cookie jar for the WebSocket connection. Uses the default VU cookie jar if not specified.
object
Custom HTTP headers to include in the WebSocket handshake request.
object
Custom metric tags for filtering results and setting thresholds.
WebSocket Metrics
k6 automatically collects WebSocket-specific metrics: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