No results for

Powered byAlgolia

Socket is a WebSocket client to interact with a WebSocket connection. You can use it to listen various events happening on the WebSocket connection and send messages to the server. Additionally, you can use socket.setTimeout() and socket.setInterval() to execute code in the background, or repeatedly, while the WebSocket connection is open.

Socket.close()Close the WebSocket connection.
Socket.on(event, callback)Set up an event listener on the connection for any of the following events:
- open
- message
- ping
- pong
- close
- error. a ping.
Socket.send(data)Send data.
Socket.setInterval(callback, interval)Call a function repeatedly at certain intervals, while the connection is open.
Socket.setTimeout(callback, period)Call a function with a delay, if the connection is open.

WebSocket built-in metrics

k6 will automatically collect some metrics when interacting with a WebSocket service through the k6/ws API.

Metric nameTypeDescription
ws_connectingTrendTotal duration for the WebSocket connection request.
ws_session_durationTrendDuration of the WebSocket session. Time between the start of the connection and the end of the VU execution.
ws_sessionsCounterTotal number of started WebSocket sessions.
ws_pingTrendDuration between a ping request and its pong reception
ws_msgs_sentCounterTotal number of messages sent through Socket.send(data)
ws_msgs_receivedCounterTotal number of received messages Socket.on('message', callback).

Check out the Results output article for more information about how to process the metric information.


import ws from 'k6/ws';
import { check } from 'k6';
export default function () {
var url = 'ws://';
var params = { tags: { my_tag: 'hello' } };
var response = ws.connect(url, params, function (socket) {
socket.on('open', function open() {
socket.setInterval(function timeout() {;
console.log('Pinging every 1sec (setInterval test)');
}, 1000);
socket.on('ping', function () {
socket.on('pong', function () {
socket.on('pong', function () {
// Multiple event handlers on the same event
console.log('OTHER PONG!');
socket.on('message', function (message) {
console.log(`Received message: ${message}`);
socket.on('close', function () {
socket.on('error', function (e) {
if (e.error() != 'websocket: close sent') {
console.log('An unexpected error occured: ', e.error());
socket.setTimeout(function () {
console.log('2 seconds passed, closing the socket');
}, 2000);
check(response, { 'status is 101': (r) => r && r.status === 101 });
//VU execution won't be completely finished until the connection is closed.