Skip to main content
k6 provides comprehensive support for testing WebSocket connections through the k6/ws module, enabling you to test real-time communication, bidirectional messaging, and WebSocket server performance.

Basic WebSocket Connection

Connect to a WebSocket server and handle events:
The WebSocket connection blocks the VU execution until the socket is closed or an error occurs. This is by design to maintain state during the connection lifecycle.

WebSocket Events

The socket object emits several events you can listen to:
Triggered when the connection is established.

Sending Messages

Send messages to the WebSocket server:

Ping/Pong and Keep-Alive

Implement keep-alive mechanisms using ping/pong frames:

Multiple Event Handlers

You can register multiple handlers for the same event:

Connection Parameters

Configure WebSocket connections with various parameters:

Available Parameters

Response Object

The ws.connect() function returns a response object with connection information:

Testing Scenarios

Error Handling

Properly handle errors and connection failures:
WebSocket connections in the init context are not supported. Always use WebSockets within the default function or other VU-scoped functions.

Metrics

k6 automatically collects WebSocket metrics:
  • ws_connecting - Time spent establishing the connection
  • ws_session_duration - Total session duration
  • ws_msgs_sent - Number of messages sent
  • ws_msgs_received - Number of messages received
  • ws_ping - Ping timing

Best Practices

  1. Always close connections explicitly to free up resources
  2. Handle all error cases to ensure test reliability
  3. Use tags to categorize different WebSocket endpoints
  4. Implement timeouts to prevent infinite connections
  5. Monitor message rates to avoid overwhelming the server
  6. Test reconnection logic by intentionally closing connections