skip to Main Content

I have a web app that uses a WebSocket client to connect to a single WebSocket server.

How can I have this WebSocket client connect to another WebSocket server at the same time?

I need to receive data from two different sources (2 different WebSocket servers).

ws = new WebSocket(url 1, url 2);

2

Answers


  1. const WebSocket = require('ws');
    
    const ws1 = new WebSocket('ws://server1-address');
    ws1.on('message', function(data) {
        console.log('Message from server 1:', data);
    });
    
    const ws2 = new WebSocket('ws://server2-address');
    ws2.on('message', function(data) {
        console.log('Message from server 2:', data);
    });
    
    ws1.send('Hello, server 1!');
    ws2.send('Hello, server 2!');
    
    Login or Signup to reply.
  2. How can I have this WebSocket client connect to another WebSocket server at the same time?

    You can’t. A WebSocket object can connect to only 1 server at a time. For what you want, you will need to create multiple WebSocket objects, one for each server.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search