> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/grafana/k6/llms.txt
> Use this file to discover all available pages before exploring further.

# WebSocket Testing

> Test WebSocket connections with k6

## Basic WebSocket Test

k6 provides a dedicated `k6/ws` module for WebSocket testing:

```javascript theme={null}
import ws from "k6/ws";
import { check } from "k6";

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

    var 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('pong', function () {
            // Multiple event handlers on the same event
            console.log("OTHER PONG!");
        });

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

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

        socket.on('error', function (e) {
            if (e.error() != "websocket: close sent") {
                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 });
};
```

## WebSocket Event Handlers

The WebSocket socket supports several event handlers:

<Steps>
  <Step title="Connection events">
    Handle connection lifecycle:

    ```javascript theme={null}
    socket.on('open', function() {
        console.log('WebSocket connection established');
        socket.send('Hello Server!');
    });

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

    socket.on('error', function(e) {
        console.log('WebSocket error:', e.error());
    });
    ```
  </Step>

  <Step title="Message events">
    Handle incoming messages:

    ```javascript theme={null}
    socket.on('message', function(data) {
        console.log('Received message:', data);
        // Process the message and optionally send a response
        socket.send('Acknowledged');
    });
    ```
  </Step>

  <Step title="Ping/Pong events">
    Handle WebSocket ping/pong frames:

    ```javascript theme={null}
    socket.on('ping', function() {
        console.log('Received ping from server');
    });

    socket.on('pong', function() {
        console.log('Received pong from server');
    });
    ```
  </Step>
</Steps>

## Timing Functions

k6 WebSockets support timing functions to control message flow:

<CodeGroup>
  ```javascript setInterval theme={null}
  // Send periodic messages
  socket.setInterval(function() {
      socket.ping();
      console.log('Sending periodic ping');
  }, 1000); // Every 1 second
  ```

  ```javascript setTimeout theme={null}
  // Send a delayed message
  socket.setTimeout(function() {
      console.log('Delayed action');
      socket.send('Delayed message');
  }, 5000); // After 5 seconds
  ```

  ```javascript Close after duration theme={null}
  // Close connection after specified time
  socket.setTimeout(function() {
      console.log('Test duration complete, closing connection');
      socket.close();
  }, 30000); // Close after 30 seconds
  ```
</CodeGroup>

## Measuring Latency

Measure round-trip time for WebSocket messages:

```javascript theme={null}
import ws from "k6/ws";
import { check } from "k6";

export default function() {
    let url = "ws://echo.websocket.org";
    
    ws.connect(url, function(socket) {
        socket.on('open', function() {
            // Send timestamp
            socket.send(Date.now().toString());
        });
        
        socket.on('message', function(data) {
            // Calculate roundtrip time
            let latency = Date.now() - parseInt(data);
            console.log(`Roundtrip time: ${latency} ms`);
            
            // Send next message after delay
            socket.setTimeout(function() {
                socket.send(Date.now().toString());
            }, 500);
        });
        
        socket.setTimeout(function() {
            socket.close();
        }, 10000);
    });
}
```

<Note>
  WebSocket connections remain open during the test iteration, making them ideal for testing real-time applications.
</Note>
