Skip to main content
The 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

The k6/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

import ws from 'k6/ws';

API Reference

Functions

connect(url, params, callback)
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:
url
string
required
WebSocket URL (e.g., wss://echo.websocket.org)
params
Params
Connection parameters (headers, cookies, compression, tags)
callback
function
required
Function called when the WebSocket connection is initiated. Receives a Socket object.
Returns:
response
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

Socket.close()
function
Closes the WebSocket connection.
Socket.on(event, callback)
function
Sets up an event listener on the connection.Events:
  • open - Connection established
  • message - Text message received
  • binaryMessage - Binary message received
  • ping - Ping received
  • pong - Pong received
  • close - Connection closed
  • error - Error occurred
Parameters:
event
string
required
Event name to listen for
callback
function
required
Handler function for the event
Socket.ping()
function
Sends a ping frame to the server.
Socket.send(data)
function
Sends string data through the WebSocket.Parameters:
data
string
required
String data to send
Socket.sendBinary(data)
function
Sends binary data through the WebSocket.Parameters:
data
ArrayBuffer
required
Binary data to send
Socket.setInterval(callback, interval)
function
Calls a function repeatedly at specified intervals while the connection is open.Parameters:
callback
function
required
Function to call repeatedly
interval
number
required
Interval in milliseconds
Socket.setTimeout(callback, delay)
function
Calls a function after a delay if the connection is still open.Parameters:
callback
function
required
Function to call after delay
delay
number
required
Delay in milliseconds

Connection Parameters

Params Object

compression
string
Compression algorithm to use. Currently only "deflate" is supported.
jar
http.CookieJar
Cookie jar for the WebSocket connection. Uses the default VU cookie jar if not specified.
headers
object
Custom HTTP headers to include in the WebSocket handshake request.
tags
object
Custom metric tags for filtering results and setting thresholds.

Connection Lifecycle

Calling connect() will block the VU until the WebSocket connection is closed by one of:
  1. Remote host close event
  2. Socket.close() call
  3. k6 VU interruption (test end, CLI command)

Examples

Basic WebSocket Connection

import ws from 'k6/ws';

export default function () {
  const url = 'wss://echo.websocket.org';
  const resp = ws.connect(url, null, function (socket) {
    socket.on('open', function () {
      console.log('WebSocket connection established!');
      socket.close();
    });
  });
}

Custom Headers and Parameters

import ws from 'k6/ws';
import { check } from 'k6';

export default function () {
  const url = 'wss://echo.websocket.org';
  
  const params = {
    headers: {
      'X-My-Header': 'k6-test',
    },
    tags: {
      test_type: 'websocket',
    },
  };

  const res = ws.connect(url, params, function (socket) {
    socket.on('open', function open() {
      console.log('Connected with custom headers');
      socket.send('Hello with custom headers!');
    });

    socket.on('message', function (message) {
      console.log(`Received: ${message}`);
      socket.close();
    });
  });

  check(res, { 'status is 101': (r) => r && r.status === 101 });
}

WebSocket Metrics

k6 automatically collects WebSocket-specific metrics:
MetricTypeDescription
ws_connectingTrendTime to establish connection
ws_session_durationTrendTotal session duration
ws_sessionsCounterTotal number of sessions
ws_msgs_sentCounterMessages sent
ws_msgs_receivedCounterMessages received
ws_pingTrendPing round-trip time

Comparison with k6/websockets

Featurek6/wsk6/websockets
Event LoopLocal (blocks VU)Global (non-blocking)
Concurrent ConnectionsOne per VUMultiple per VU
API StyleCallback-basedBrowser WebSocket API
PerformanceGood for single connectionsBetter for multiple connections
Use CaseTraditional WebSocket testingModern async WebSocket testing

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

Build docs developers (and LLMs) love