簡體   English   中英

使用服務器發送的事件:如何存儲與客戶端的連接?

[英]Using server-sent events : how to store a connection to a client?

在這里,

我已經在 react-native 應用程序和 NodeJS 服務器之間建立了 SSE 連接。 我按照一些指南在客戶端設置它,填充EventSource等等,這非常簡單。 但是在服務器端,我在找出如何存儲與客戶端的連接時遇到了一些問題。 我選擇將響應存儲在global object 中,但我覺得這不是正確的做法。 有人可以建議嗎?

這是我下面的代碼


const SSE_RESPONSE_HEADER = {
  'Connection': 'keep-alive',
  'Content-Type': 'text/event-stream',
  'Cache-Control': 'no-cache',
  'X-Accel-Buffering': 'no'
};

const getUserId = (req, from) => {
  try {
    // console.log(from, req.body, req.params)
    if (!req) return null;
    if (Boolean(req.body) && req.body.userId) return req.body.userId;
    if (Boolean(req.params) && req.params.userId) return req.params.userId;
    return null
  } catch (e) {
    console.log('getUserId error', e)
    return null;
  }
}

global.usersStreams = {}

exports.setupStream = (req, res, next) => {

  let userId = getUserId(req);
  if (!userId) {
    next({ message: 'stream.no-user' })
    return;
  }

  // Stores this connection
  global.usersStreams[userId] = {
    res,
    lastInteraction: null,
  }

  // Writes response header.
  res.writeHead(200, SSE_RESPONSE_HEADER);

  // Note: Heatbeat for avoidance of client's request timeout of first time (30 sec)
  const heartbeat = {type: 'heartbeat'}
  res.write(`data: ${JSON.stringify(heartbeat)}\n\n`);
  global.usersStreams[userId].lastInteraction = Date.now()

  // Interval loop
  const maxInterval = 55000;
  const interval = 3000;
  let intervalId = setInterval(function() {
    if (!global.usersStreams[userId]) return;
    if (Date.now() - global.usersStreams[userId].lastInteraction < maxInterval) return;
    res.write(`data: ${JSON.stringify(heartbeat)}\n\n`);
    global.usersStreams[userId].lastInteraction = Date.now()
  }, interval);


  req.on("close", function() {
    let userId = getUserId(req, 'setupStream on close');
    // Breaks the interval loop on client disconnected
    clearInterval(intervalId);
    // Remove from connections
    delete global.usersStreams[userId];
  });

  req.on("end", function() {
    let userId = getUserId(req, 'setupStream on end');
    clearInterval(intervalId);
    delete global.usersStreams[userId];
  });

};

exports.sendStream = async (userId, data) => {
  if (!userId) return;
  if (!global.usersStreams[userId]) return;
  if (!data) return;

  const { res } = global.usersStreams[userId];

  res.write(`data: ${JSON.stringify({ type: 'event', data })}\n\n`);
  global.usersStreams[userId].lastInteraction = Date.now();

};

我的第一個提示是簡單地擺脫global 在模塊的閉包中有一個變量是可以的。 您的模塊可以封裝這個“全局”state,而不需要所有其他模塊全局訪問它。

const usersStreams = {};

其次,同一個用戶建立多個連接可能並非不可能。 我建議,如果您在userId上鍵入這些連接,則應該將這些鍵的userStreams中的值設置為 collections 以便您可以寫入多個。 要么,要么你需要一個更獨特的密鑰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM