While we intend to keep experimental modules as stable as possible, we may need to introduce breaking changes. This could happen at future k6 releases until the module becomes fully stable and graduates as a k6 core module. For more information, refer to the extension graduation process.
Experimental modules maintain a high level of stability and follow regular maintenance and security measures. Feel free to open an issue if you have any feedback or suggestions.
This experimental API implements the browser WebSocket API with additional k6-specific functionalities (cookies, tags, headers and so on).
The main difference between this module and k6/ws is that this module uses a global event loop instead of a local one.
A global event loop lets a single VU have multiple concurrent connections, which improves performance.
The WebSocket API is not fully implemented, and we’re working on it, but we believe it’s usable for most users. So whether you’re writing a new WebSocket test, or currently using the k6/ws module, we invite you to give it a try, and report any issues in the project’s issue tracker. Our midterm goal is to make this module part of k6 core, and long-term to replace the k6/ws module.
Interface that represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream.
A WebSocket instance also has the following properties:
Class/Property
Description
WebSocket.readyState
The current state of the connection. Could be one of the four states.
WebSocket.url
The URL of the connection as resolved by the constructor.
WebSocket.bufferedAmount
The number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.
WebSocket.binaryType
The binaryType controls the type of binary data being received over the WebSocket connection. Use "blob" to receive it as Blob, or "arraybuffer" to receive it as ArrayBuffer. The default value is "blob".
k6 takes specific measurements for Websockets.
For the complete list, refer to the Metrics reference.
Example
This example shows:
How a single VU can run multiple WebSockets connections asynchronously.
How to use the timeout and interval functions to stop the connections after some period.
JavaScript
import{ randomString, randomIntBetween }from'https://jslib.k6.io/k6-utils/1.1.0/index.js';import{ WebSocket }from'k6/experimental/websockets';const chatRoomName ='publicRoom';// choose any chat room nameconst sessionDuration =randomIntBetween(5000,60000);// user session between 5s and 1mexportdefaultfunction(){for(let i =0; i <4; i++){startWSWorker(i);}}functionstartWSWorker(id){// create a new websocket connectionconst ws =newWebSocket(`wss://test-api.k6.io/ws/crocochat/${chatRoomName}/`);
ws.binaryType ='arraybuffer';
ws.addEventListener('open',()=>{// change the user name
ws.send(JSON.stringify({event:'SET_NAME',new_name:`Croc ${__VU}:${id}`}));// listen for messages/errors and log them into console
ws.addEventListener('message',(e)=>{const msg =JSON.parse(e.data);if(msg.event ==='CHAT_MSG'){
console.log(`VU ${__VU}:${id} received: ${msg.user} says: ${msg.message}`);}elseif(msg.event ==='ERROR'){
console.error(`VU ${__VU}:${id} received:: ${msg.message}`);}else{
console.log(`VU ${__VU}:${id} received unhandled message: ${msg.message}`);}});// send a message every 2-8 secondsconst intervalId =setInterval(()=>{
ws.send(JSON.stringify({event:'SAY',message:`I'm saying ${randomString(5)}`}));},randomIntBetween(2000,8000));// say something every 2-8 seconds// after a sessionDuration stop sending messages and leave the roomconst timeout1id =setTimeout(function(){clearInterval(intervalId);
console.log(`VU ${__VU}:${id}: ${sessionDuration}ms passed, leaving the chat`);
ws.send(JSON.stringify({event:'LEAVE'}));}, sessionDuration);// after a sessionDuration + 3s close the connectionconst timeout2id =setTimeout(function(){
console.log(`Closing the socket forcefully 3s after graceful LEAVE`);
ws.close();}, sessionDuration +3000);// when connection is closing, clean up the previously created timers
ws.addEventListener('close',()=>{clearTimeout(timeout1id);clearTimeout(timeout2id);
console.log(`VU ${__VU}:${id}: disconnected`);});});}