You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中基于IEXCloud API实现多SSE连接的方案咨询

How to Create Independent Multi-SSE Connections in Node.js for IEXCloud

Got it, let's tackle this multi-SSE connection problem you're facing. The core issue with your current code is that it uses global variables (like stream and partialMessage) which would conflict if you tried to duplicate the logic for a second connection. The fix is to encapsulate each connection's state and logic into a reusable function, so each stream operates independently.

Here's a step-by-step solution tailored to your use case:

Key Approach

We'll create a factory function that generates a self-contained SSE stream for any set of symbols. Each instance will maintain its own connection, partial message buffer, and data handling logic—no cross-contamination between streams.

Full Implementation Code

const request = require('request'); // Ensure you have the request library installed

// Factory function to create an independent SSE stream
function createIEXSSEStream(token, symbols, handleStreamData) {
  let stream;
  let partialMessage = ''; // Isolated per stream, no global conflicts

  // Build the stream URL for the given symbols
  const streamUrl = `https://cloud-sse.iexapis.com/stable/stocksUSNoUTP?token=${token}&symbols=${symbols.join(',')}`;

  // Internal connect/reconnect logic
  function connect() {
    stream = request({
      url: streamUrl,
      headers: { 'Content-Type': 'text/event-stream' }
    });

    stream.on('socket', () => {
      console.log(`✅ Connected to stream: ${symbols.join(',')}`);
    });

    stream.on('end', () => {
      console.log(`🔄 Stream ended for ${symbols.join(',')} — reconnecting...`);
      connect();
    });

    stream.on('complete', () => {
      console.log(`🔄 Stream completed for ${symbols.join(',')} — reconnecting...`);
      connect();
    });

    stream.on('error', (err) => {
      console.error(`❌ Error in stream ${symbols.join(',')}:`, err);
      connect();
    });

    // Data parsing logic, isolated per stream
    stream.on('data', (response) => {
      let chunk = response.toString();
      let cleanedChunk = chunk.replace(/data: /g, '');

      if (partialMessage) {
        cleanedChunk = partialMessage + cleanedChunk;
        partialMessage = '';
      }

      const messageChunks = cleanedChunk.split('\r\n\r\n');
      messageChunks.forEach((message) => {
        if (!message) return;

        try {
          const quote = JSON.parse(message)[0];
          handleStreamData(quote); // Pass data to custom handler
        } catch (error) {
          partialMessage = message; // Handle incomplete messages
        }
      });
    });
  }

  // Initialize the stream
  connect();
}

// --- Usage Example ---
const yourIEXToken = 'YOUR_IEX_CLOUD_TOKEN_HERE';

// First stream: Tech stocks (AAPL, AMZN, TWTR)
createIEXSSEStream(yourIEXToken, ['aapl', 'amzn', 'twtr'], (quote) => {
  console.log('\n📈 Tech Stock Update:', {
    symbol: quote.symbol,
    price: quote.latestPrice,
    time: new Date(quote.latestUpdate)
  });
  // Add custom logic here (e.g., save to a tech-stocks database table)
});

// Second stream: Other stocks (ISF, AVV, NFLX)
createIEXSSEStream(yourIEXToken, ['isf', 'avv', 'nflx'], (quote) => {
  console.log('\n📉 Other Stock Update:', {
    symbol: quote.symbol,
    price: quote.latestPrice,
    time: new Date(quote.latestUpdate)
  });
  // Add custom logic here (e.g., send alerts for NFLX price changes)
});

// Keep the Node.js process running (alternative to your wait() function)
process.stdin.resume();

What This Solves

  • Isolated State: Each stream has its own stream and partialMessage variables, so one connection's partial messages or disconnects won't affect the other.
  • Reusable Logic: You can create as many streams as needed by calling createIEXSSEStream with different symbols and handlers.
  • Independent Data Handling: The handleStreamData callback lets you define unique processing for each stream (e.g., saving to different databases, sending targeted alerts).
  • Robust Reconnection: Each stream handles its own reconnection logic independently—if one stream drops, the other keeps running uninterrupted.

Note: I fixed the URL from using &symbols to &symbols—the former is HTML-encoded, which isn't needed in a Node.js request URL.

内容的提问来源于stack exchange,提问作者Priyank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 19:19:11