How to receive server data response before sending another message during websocket test?

Hello, I’m working on performance testing, which is testing websocket application. I have a test, which is almost similar to example websocket test on k6 page here: WebSockets

my test code is here :

import ws from 'k6/ws';
import { check } from 'k6';

export default function () {
    const CoreURL = 'localhost:51110';
    const url = 'ws://' + CoreURL + '/ws';
    const params = { tags: { my_tag: 'hello' } };
    const message1 = "some message data here"
    const message2 = "some message data here"
    const message3 = "some message data here"

  const res = ws.connect(url, params, function (socket) {
    socket.on('open', function(){
      console.log("connected");

     socket.send(message1);
     socket.send(message2);
     socket.send(message3);
      });

     socket.on('binaryMessage', function(data) {
      *parsing data here into messages*
    });


   socket.on('close', () => console.log('disconnected'));
  });

  check(res, { 'status is 101': (r) => r && r.status === 101 });
}

Both sections socket.on(‘open’) and socket.on(‘binaryMessage’) are working, but my problem is, that I need send message1 in socket.on(‘open’) function, then receive data from server in socket.on(‘binaryMessage’) function and parse them into message2 and then send message2 socket.on(‘open’) function. I thought that socket.on() works as some kind of observer, so when I send a message I will immediately receive response data, but in this case first socket.on(‘open’) is executed and after all code is executed here, there comes code in socket.on(‘binaryMessage’) for all messages. I have also tried put some sleep() between socket.send(message), but as I wrote I will get all responses after the all code in socket.on(‘open’) function is executed.

Is there any way to solve my problem ?

Have a great day.

Adam

Hi @Strongy, Welcome to the community forum!

I did not understand what you were trying to say with “observer” here.

If you just want to send your message after you get a binaryMessage back and to use the message - you should be calling socket.send(message2) in the on binaryMessage.

The .on functions are basically callbacks on events - when the event is observed they will be called, and when they end a new event can be observed. As js is single threaded by design.

I would also like to point out that the current k6/ws API is maintenance mode and what is recommended is to use k6/experimental/websockets which is similar/copied from the WebSocket API that browsers have.

That API also happens to be more versatile and using an actual global (for the VU) event loop, instead of the local one the k6/ws is stuck with due to history :(.

Hope this helps you and sorry for the slow response

2 Likes