Websocket disconnects after 15 seconds

Hi!

I’m having trouble running a websocket for more than 15 seconds.

The code is from documentation:

  const socketUrl = `${resBody.url.replace('https', 'wss')}&id=${connectionId}`;

  res = ws.connect(socketUrl, params, function (socket) {
    socket.on('open', function() {
    	console.log('connected');
    	
        socket.setInterval(function timeout() {
	      socket.ping();
	    }, 1000); 
	    
	    var payload = JSON.stringify({
	      'protocol': 'json',
	      'version': 1
	    });
    	socket.send(payload);	       	
    });
    socket.on('message', (data) => console.log('Message received: ', data));
    socket.on('close', () => console.log('disconnected'));
    socket.on('error', (e) => console.log('Error: ', e.error()));
    socket.on('ping',  function() {
      console.log('ping');
      socket.pong();
    });
    socket.on('pong',  () => console.log('pong'));
    socket.on('priceupdates', (data) => console.log('PriceUpdates: ', data));

    socket.setTimeout(function () {
	  console.log('Timeout');
      socket.close();
    }, 1000 * 60 * 100);
  });
	
  check(res, { 'status is 101': (r) => r && r.status === 101 });

and the output:

Run command:

k6 run --vus 1 --iterations 1 --duration 1m --min-iteration-duration 30s live_prices.js

Any ideas? I need to run it for 15 minutes minimum.

Found that we need to send a handshake message right after the connection is established

var payload = JSON.stringify({
  'protocol': 'json',
  'version': 1
});

but with Record Ending char (ASCII char 30) at the end.

So I ended up sending:

const endOfRecord = String.fromCharCode(30);

var payload = JSON.stringify({
  'protocol': 'json',
  'version': 1
}) + endOfRecord;

After that everything started working properly.

1 Like