javascriptnode.jswebsocket

How to use WebSocket multiple connection


I'm making a simple app that requires Websocket with JavaScript & NodeJS. I'm using the WS NPM package.

The issue is, I want to use two connection in the same project, I have both defined at the top of my file like so:

const ws = new WebSocket("wss://pumpportal.fun/api/data");
const wss = new WebSocket("wss://pumpportal.fun/api/data");

ws.on("open", function open() {
  // Subscribing to token creation events
  let payload = {
    method: "subscribeNewToken",
  };
  ws.send(JSON.stringify(payload));
});

And then, after closing the first WebSocket connect, I need to start the second WebSocket process. I'm doing it like so:

// Closing first connection
ws.on("close", (event) => {
     // Trying to open second connection on first connection closed
     wss.on("open", function open() {
        console.log("WSS Action...");
        // Subscribing to trades on tokens
        let payload = {
            method: "subscribeTokenTrade",
                     keys: [tokenMetadata.mint],
            };

         wss.send(JSON.stringify(payload));
     });

But the second connection isn't opening, any help as to how I can do this?

Trying to use two websocket connection, but it's not working. Any help on how I can do it will be appreciated!


Solution

  • You need to call new Websocket after closing the last WS. In your current solution you open two websockets at the same time.

    function secondWebSocket() {
        const secondWs = new WebSocket("wss://pumpportal.fun/api/data");
    
        secondWs.on("open", function() {
            console.log("WSS Action...");
            // Subscribing to trades on tokens
            let payload = {
                method: "subscribeTokenTrade",
                keys: [tokenMetadata.mint],
            };
    
            secondWs.send(JSON.stringify(payload));
        })
    }
    
    function firstWebSocket() {
        const firstWs = new WebSocket("wss://pumpportal.fun/api/data");
    
        firstWs.on("open", function open() {
            // Subscribing to token creation events
            let payload = {
                method: "subscribeNewToken",
            };
            firstWs.send(JSON.stringify(payload));
        })
        firstWs.on("close", function() {
            secondWebSocket();
        })
    }
    firstWebSocket();