k6/ws module provides a WebSocket client implementing the WebSocket protocol. This module uses a local event loop that blocks VU execution until the connection is closed.
For better performance with multiple concurrent connections, consider using
k6/websockets which uses a global event loop.Overview
Thek6/ws module creates WebSocket connections that block test execution until closed. This is suitable for testing scenarios where each VU maintains a single long-lived WebSocket connection.
Importing the Module
API Reference
Functions
function
Creates a WebSocket connection and provides a Socket client to interact with the service. The method blocks test finalization until the connection is closed.Parameters:Returns:
string
required
WebSocket URL (e.g.,
wss://echo.websocket.org)Params
Connection parameters (headers, cookies, compression, tags)
function
required
Function called when the WebSocket connection is initiated. Receives a Socket object.
Response
HTTP Response object from the WebSocket handshake
Socket Class
The Socket object is passed to the callback function and provides methods to interact with the WebSocket connection.Methods
function
Closes the WebSocket connection.
function
Sets up an event listener on the connection.Events:
open- Connection establishedmessage- Text message receivedbinaryMessage- Binary message receivedping- Ping receivedpong- Pong receivedclose- Connection closederror- Error occurred
string
required
Event name to listen for
function
required
Handler function for the event
function
Sends a ping frame to the server.
function
function
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.
Connection Lifecycle
Callingconnect() will block the VU until the WebSocket connection is closed by one of:
- Remote host close event
Socket.close()call- k6 VU interruption (test end, CLI command)
Examples
Basic WebSocket Connection
Custom Headers and Parameters
WebSocket Metrics
k6 automatically collects WebSocket-specific metrics:Comparison with k6/websockets
Related Resources
k6/websockets
Modern WebSocket API with global event loop
Params
WebSocket connection parameters
WebSocket Testing Guide
Learn WebSocket testing patterns
Metrics Reference
WebSocket metrics documentation