Skip to main content
The k6/ws module provides WebSocket client functionality for testing real-time applications.

Functions

connect(url, [params], callback)

Establishes a WebSocket connection.
url
string
WebSocket URL (ws:// or wss://)
params
object
Connection parameters
callback
function
Function to execute after connection is established. Receives Socket object.
response
HTTPResponse
HTTP response object from the connection handshake
import ws from 'k6/ws';
import { check } from 'k6';

export default function () {
  const url = 'ws://echo.websocket.org';
  const response = ws.connect(url, function (socket) {
    socket.on('open', () => console.log('connected'));
    socket.on('message', (data) => console.log('Message:', data));
    socket.on('close', () => console.log('disconnected'));
  });

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

Connection Parameters

headers
object
Custom headers for the WebSocket handshake
tags
object
Custom tags for metrics
jar
CookieJar
Cookie jar to use for the connection
compression
string
Compression algorithm (deflate is supported, experimental)
const params = {
  headers: { 'Authorization': 'Bearer token' },
  tags: { name: 'websocket-test' },
};

ws.connect(url, params, function (socket) {
  // ...
});

Socket Object

The Socket object is passed to the connect callback and provides methods to interact with the WebSocket.

Event Handlers

on(event, handler)

Registers an event handler.
event
string
Event name: open, message, binaryMessage, ping, pong, close, or error
handler
function
Function to call when event occurs
socket.on('open', function () {
  console.log('WebSocket connection established');
});

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

socket.on('binaryMessage', function (data) {
  console.log('Binary data received:', new Uint8Array(data));
});

socket.on('close', function () {
  console.log('Connection closed');
});

socket.on('error', function (e) {
  console.log('Error:', e.error());
});

Sending Messages

send(data)

Sends a text message.
data
string
Message to send
socket.send('Hello, server!');
socket.send(JSON.stringify({ type: 'message', data: 'test' }));

sendBinary(data)

Sends a binary message.
data
ArrayBuffer
Binary data to send
const data = new Uint8Array([1, 2, 3, 4]);
socket.sendBinary(data.buffer);

ping()

Sends a ping frame.
socket.ping();

Timing Functions

setTimeout(callback, delay)

Executes a function after a delay.
callback
function
Function to execute
delay
number
Delay in milliseconds
socket.setTimeout(function () {
  socket.send('Delayed message');
}, 1000);

setInterval(callback, interval)

Executes a function repeatedly at intervals.
callback
function
Function to execute
interval
number
Interval in milliseconds
socket.setInterval(function () {
  socket.ping();
}, 5000);

Connection Control

close([code])

Closes the WebSocket connection.
code
number
WebSocket close code (default: 1001)
socket.close();
// or with custom code
socket.close(1000);

Examples

Basic WebSocket Test

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

export default function () {
  const url = 'ws://echo.websocket.org';
  const params = { tags: { my_tag: 'hello' } };

  const response = ws.connect(url, params, function (socket) {
    socket.on('open', function open() {
      console.log('connected');
      socket.send(Date.now());

      socket.setInterval(function timeout() {
        socket.ping();
        console.log('Pinging every 1sec (setInterval test)');
      }, 1000);
    });

    socket.on('ping', function () {
      console.log('PING!');
    });

    socket.on('pong', function () {
      console.log('PONG!');
    });

    socket.on('message', function (data) {
      console.log(`Roundtrip time: ${Date.now() - data} ms`);
      socket.setTimeout(function timeout() {
        socket.send(Date.now());
      }, 500);
    });

    socket.on('close', function () {
      console.log('disconnected');
    });

    socket.on('error', function (e) {
      console.log('An unexpected error occurred: ', e.error());
    });

    socket.setTimeout(function () {
      console.log('2 seconds passed, closing the socket');
      socket.close();
    }, 2000);
  });

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

Chat Application Test

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

export default function () {
  const url = 'wss://chat.example.com/ws';

  const response = ws.connect(url, function (socket) {
    socket.on('open', function () {
      // Join chat room
      socket.send(JSON.stringify({
        type: 'join',
        room: 'general',
        username: `user-${__VU}`,
      }));
    });

    socket.on('message', function (data) {
      const msg = JSON.parse(data);
      console.log(`Received: ${msg.type}`);

      if (msg.type === 'welcome') {
        // Send a message
        socket.send(JSON.stringify({
          type: 'message',
          text: 'Hello from k6!',
        }));
      }
    });

    socket.setTimeout(function () {
      socket.close();
    }, 10000);
  });

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

Binary Data Transfer

import ws from 'k6/ws';

export default function () {
  ws.connect('ws://echo.websocket.org', function (socket) {
    socket.on('open', function () {
      // Send binary data
      const data = new Uint8Array([1, 2, 3, 4, 5]);
      socket.sendBinary(data.buffer);
    });

    socket.on('binaryMessage', function (data) {
      const arr = new Uint8Array(data);
      console.log('Received binary:', arr);
      socket.close();
    });
  });
}
WebSocket connections cannot be used in the init context. They must be created in the VU context (default function).

Build docs developers (and LLMs) love