Here's a load test for CrocoChat - a WebSocket chat API available on https://test-api.k6.io/.
Multiple VUs join a chat room and discuss various things for up to 1 minute, after which they disconnect.
Each VU receives messages sent by all chat participants.
crocochat.js
1import { randomString, randomIntBetween } from 'https://jslib.k6.io/k6-utils/1.2.0/index.js';2import ws from 'k6/ws';3import { check, sleep } from 'k6';4
5const sessionDuration = randomIntBetween(10000, 60000); // user session between 10s and 1m6const chatRoomName = 'publicRoom'; // choose your chat room name7
8export const options = {9 vus: 10,10 iterations: 10,11};12
13export default function () {14 const url = `wss://test-api.k6.io/ws/crocochat/${chatRoomName}/`;15 const params = { tags: { my_tag: 'my ws session' } };16
17 const res = ws.connect(url, params, function (socket) {18 socket.on('open', function open() {19 console.log(`VU ${__VU}: connected`);20
21 socket.send(JSON.stringify({ event: 'SET_NAME', new_name: `Croc ${__VU}` }));22
23 socket.setInterval(function timeout() {24 socket.send(JSON.stringify({ event: 'SAY', message: `I'm saying ${randomString(5)}` }));25 }, randomIntBetween(2000, 8000)); // say something every 2-8seconds26 });27
28 socket.on('ping', function () {29 console.log('PING!');30 });31
32 socket.on('pong', function () {33 console.log('PONG!');34 });35
36 socket.on('close', function () {37 console.log(`VU ${__VU}: disconnected`);38 });39
40 socket.on('message', function (message) {41 const msg = JSON.parse(message);42 if (msg.event === 'CHAT_MSG') {43 console.log(`VU ${__VU} received: ${msg.user} says: ${msg.message}`);44 } else if (msg.event === 'ERROR') {45 console.error(`VU ${__VU} received:: ${msg.message}`);46 } else {47 console.log(`VU ${__VU} received unhandled message: ${msg.message}`);48 }49 });50
51 socket.setTimeout(function () {52 console.log(`VU ${__VU}: ${sessionDuration}ms passed, leaving the chat`);53 socket.send(JSON.stringify({ event: 'LEAVE' }));54 }, sessionDuration);55
56 socket.setTimeout(function () {57 console.log(`Closing the socket forcefully 3s after graceful LEAVE`);58 socket.close();59 }, sessionDuration + 3000);60 });61
62 check(res, { 'Connected successfully': (r) => r && r.status === 101 });63}