No results for

Powered byAlgolia

WebSockets

suggest edits

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.1.0/index.js";
2import ws from 'k6/ws';
3import { check, sleep } from 'k6';
4
5let sessionDuration = randomIntBetween(10000, 60000); // user session between 10s and 1m
6let chatRoomName = 'publicRoom'; // choose your chat room name
7
8export let options = {
9 vus: 10,
10 iterations: 10,
11};
12
13export default function () {
14 let url = `wss://test-api.k6.io/ws/crocochat/${chatRoomName}/`;
15 let params = { tags: { my_tag: 'my ws session' } };
16
17 let 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-8seconds
26 });
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 let msg = JSON.parse(message);
42 if(msg.event === 'CHAT_MSG'){
43 console.log(`VU ${__VU} received: ${msg.user} says: ${msg.message}`)
44 }
45 else if(msg.event === 'ERROR'){
46 console.error(`VU ${__VU} received:: ${msg.message}`)
47 }
48 else{
49 console.log(`VU ${__VU} received unhandled message: ${msg.message}`)
50 }
51 });
52
53 socket.setTimeout(function () {
54 console.log(`VU ${__VU}: ${sessionDuration}ms passed, leaving the chat`);
55 socket.send(JSON.stringify({'event': 'LEAVE'}));
56
57 }, sessionDuration);
58
59 socket.setTimeout(function () {
60 console.log(`Closing the socket forcefully 3s after graceful LEAVE`);
61 socket.close();
62 }, sessionDuration+3000);
63 });
64
65 check(res, { 'Connected successfully': (r) => r && r.status === 101 });
66}