Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a Websocket example #53

Merged
merged 1 commit into from
Jan 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions k6/foundations/13.basic.websockets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { sleep } from 'k6';
import { WebSocket } from 'k6/experimental/websockets';
import { setInterval } from 'k6/experimental/timers';
import { Counter } from "k6/metrics";

let BASE_URL = __ENV.BASE_URL || 'http://localhost:3333';

BASE_URL = BASE_URL.replace("https://", "wss://");
BASE_URL = BASE_URL.replace("http://", "ws://");

export const options = {
scenarios: {
receiver: {
exec: "receiver",
executor: "ramping-vus",
executor: 'shared-iterations',
iterations: 1,
maxDuration: '1m',
},
sender: {
exec: "sender",
executor: 'shared-iterations',
iterations: 20,
vus: 10,

// delay the start to get the receiver ready
startTime: '2s',
},

}
};

// send two WS messages
export function sender() {
const ws = new WebSocket(`${BASE_URL}/ws`);
ws.addEventListener('open', () => {
ws.send(JSON.stringify({ user: `VU ${__VU}`, msg: "order_pizza" }));
sleep(0.2);
ws.send(JSON.stringify({ user: `VU ${__VU}`, msg: "pizza_status?" }));
sleep(0.1);
ws.close();
});
}

export function receiver () {

// Close the WS connection to end the iteration once the number of expected messages is received.

// Be aware that a local counter (`messageCounter`) is valid here because only one `receiver` iteration runs.
let messageCounter = 0;
const totalExpectedMessages = 20*2; // 20 iterations * 2 messages per iteration

const ws = new WebSocket(`${BASE_URL}/ws`);
ws.addEventListener('open', () => {
ws.addEventListener('message', (e) => {
const msg = JSON.parse(e.data);
console.log(`VU ${__VU} received: ${msg.user} msg: ${msg.msg}`);
messageCounter++;
if (messageCounter === totalExpectedMessages) {
ws.close();
}
});
});
}