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:- open
- message
- close
- error
- ping/pong
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
Thews.connect() function returns a response object with connection information:
Testing Scenarios
Error Handling
Properly handle errors and connection failures:Metrics
k6 automatically collects WebSocket metrics:ws_connecting- Time spent establishing the connectionws_session_duration- Total session durationws_msgs_sent- Number of messages sentws_msgs_received- Number of messages receivedws_ping- Ping timing
Best Practices
- Always close connections explicitly to free up resources
- Handle all error cases to ensure test reliability
- Use tags to categorize different WebSocket endpoints
- Implement timeouts to prevent infinite connections
- Monitor message rates to avoid overwhelming the server
- Test reconnection logic by intentionally closing connections