使用node.js管理多个Websocket客户端连接

时间:2018-11-29 16:15:11

标签: javascript node.js session websocket

我正在node中实现一个websocket客户端,我的Webhook试图处理来自聊天机器人服务的多个连接。例如:新用户收入,在外部聊天机器人服务上建立了websocket连接。 Websocket URL是通过我的代码中的XMLHttpRequest获得的。然后,我使用该URL通过ws对象(new WebSocket('wssUrlObtainedThroughAjaxRequest','default-protocol'))连接到chatbot服务。因此,每个用户都有一个WebSocket。问题是我的代码按顺序运行。因此,如果两个人向我的webhook节点发送消息,则由于并行性,事情将无法正常工作。好吧,我将在此处发布示例代码,以使其更易于理解。

const express = require('express');
const PORT = process.env.PORT || 8002;
let WebSocket = require('ws');
let CONNECTIONS = new Map();
...
...
...
const app = express()
    .use(bodyparser.urlencoded({extended: false}))
    .use(bodyparser.json());

app.post('/', (req, res) => { 
...
...
...
    } else if (req.body.type === 'MESSAGE') {

    let DM = req.body.space.name;
    let msg = req.body.message.text;

    ws = (CONNECTIONS.get(DM)!=null) ? CONNECTIONS.get(DM) : null;

    if(ws==null || ws.readyState==3){
      controlws.gerarURLWS();
      ws = new WebSocket(controlws.urlws, 'talk-protocol');
      CONNECTIONS.set(DM,ws);
    }

    // Executes on websocket openning
    ws.onopen = function (event) {
      console.log('Canal aberto;');
      keepAliveWS();
      ws.send(JSON.stringify(msgKoreAi(msg))); 
    }

    if(ws.readyState==1)
      ws.send(JSON.stringify(msgKoreAi(msg))); 

    ws.onmessage = async function (event) {
      let resp = JSON.parse(event.data);

      if (resp.type == "bot_response") {
        text = resp.message[0].component.payload.text;

        if(text==null){ // tem quick reply
          //mount card hangouts response 
          let qreplies = resp.message[0].component.payload.payload.quick_replies; 
          card = '{"sections": [{"widgets": [{"buttons": [';
          for(let i=0; i<qreplies.length; i++){
            if(i!=qreplies.length-1)
              card+='{"textButton": {"text": "'+qreplies[i].payload+'","onClick": {"action": {"actionMethodName": "'+qreplies[i].payload+'"}}}},';
            else
              card+='{"textButton": {"text": "'+qreplies[i].payload+'","onClick": {"action": {"actionMethodName": "'+qreplies[i].payload+'"}}}}';
          }      
          card+=']}]}],"name": "respostas"}';
          card = JSON.parse(card);

          text = resp.message[0].component.payload.payload.text; 
          {
            await assyncMessage(DM, text);
            await assyncMessage(DM, card);
          }
          return;
        }

        //Send assync messages if synchronous was already sent
        if(res.headersSent){
          {
            return await assyncMessage(DM, text);
          }
        }
        else
          return res.json({text});
      }
    }
    return;
  }
...
...
...
app.listen(PORT, () => {
  console.log(`Server is running in port - ${PORT}`);
});

0 个答案:

没有答案