使用 AWS ELB 连接节点服务器时 Websocket 在闲置 60 秒后关闭

2023-12-19

我有一个节点服务器在 EC2 实例上运行,客户端也在同一个 EC2 实例上运行,客户端打开 websocket 连接来与节点服务器通信,它正在 QA 和 Dev AWS 环境中工作,但相同的 Web 连接在空闲 60 秒后逐渐关闭在 prod 环境中,我在 aws 环境中的 ELB 后面运行客户端和节点服务器。

客户端代码:

ws = new WebSocket('ws://localhost:8443');
        
ws.onclose = function () {
    console.log("Websocket connection has been closed.");
    clientObj.emit('LogoffSuccess', 'LogoffSuccessfully');
};
 
ws.onerror=function(event)
{
    console.log(event.data);
};
            
ws.addEventListener('open', function (event) {
    console.log('Websocket connection has been opened');
    ws.send(JSON.stringify(loginCreds));
});
    
    

节点服务器代码如下:

const wss = new WebSocket.Server({ server: app });
const clients = {};
const idMap = {};
    
wss.on(`connection`, ws => {
  const headers = ws.upgradeReq.headers;
  const host = headers.host;
  const key = ws.upgradeReq.headers[`sec-websocket-key`];
    
  ctiServer.on(`responseMessage`, message => {
   clients[message.AgentId].send(JSON.stringify(message));
  });
    
  ws.on(`message`, message => {
    log.info(`Message received. Host: ${host}, Msg: ${message}`);
    if (JSON.parse(message).EventName === `Login`) {
      clients[JSON.parse(message).AgentId] = ws;
      idMap[key] = JSON.parse(message).AgentId;
     }
     ctiServer.processIncomingRequest(message);
  });
    
  ws.on(`close`, () => {
    log.info(`Connection closed. Host: ${host}`);

    const message = {
      EventName: `Logoff`,
      AgentId: idMap[key],
      EventData: {}
    };
        
 });
});

默认情况下,Elastic Load Balancing 将空闲超时值设置为 60 秒。因此,如果在请求进行时目标没有至少每 60 秒发送一些数据,则负载均衡器可以关闭前端连接。为了保证文件上传等耗时操作有时间完成,在每个空闲超时时间结束前至少发送1字节的数据,并根据需要增加空闲超时时间的长度。

https://docs.aws.amazon.com/elasticloadbalancing/latest/application/application-load-balancers.html#connection-idle-timeout https://docs.aws.amazon.com/elasticloadbalancing/latest/application/application-load-balancers.html#connection-idle-timeout

请注意,定期发送流量以保持连接活动最符合您的利益。您可以在应用程序负载均衡器中将空闲超时设置为最多 4000 秒,但您会发现有状态中间网络基础设施(防火墙、NAT 设备)往往会在连接实际空闲这么长时间之前重置连接。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 AWS ELB 连接节点服务器时 Websocket 在闲置 60 秒后关闭 的相关文章

随机推荐