Websockets multiple events sent and multiple event handlers on client side

Viewed 1054

Recently I started using WebSockets for Server-Client communication. The problem is when I want to send multiple types of data in a connection. Is there any way to send multiple messages events from server side to client side in a single connection and to handle them separately in the client side? Like...

wss.on('connection', function connection(ws){ 
  ws.send('message1',data1);
  ws.send('message2',data2);
  ws.send('message3',data3);
}

Data1,2,3 are different types of data(data1 is a json, data2 is a string) and I want to use them in the client side for different purposes.

1 Answers

You can create a structure which every message follows and attach the type to this structure:

wss.send(JSON.stringify({ type: 'firstName', value: 'John' }));
wss.send(JSON.stringify({ type: 'lastName', value: 'Doe' }));

Then handle the message by checking the type:

wss.on('message', ev => {
  const data = JSON.parse(ev.data);
  switch (data.type) {
    case 'firstName':
      document.getElementById('first-name').textContent = data.value;
      break;

    case 'lastName':
      document.getElementById('last-name').textContent = data.value;
      break;

    default:
      // Unknown websocket message type
  }
});
Related