简体   繁体   English

如何使用 Nexmo 建立多个 websocket 连接

[英]How to have multiple websocket connections using Nexmo

I implemented the nexmo provided example code (below) into my server.我在我的服务器中实现了 nexmo 提供的示例代码(如下)。 However, I'm running into an issue where if 2 callers ping my server, the second caller's binary data also streams into the same websocket endpoint;但是,我遇到了一个问题,如果 2 个调用者 ping 我的服务器,第二个调用者的二进制数据也会流入同一个 websocket 端点; thus resulting in two binary streams into the same websocket endpoint.从而导致两个二进制流进入同一个 websocket 端点。 How could I implement nexmo so that each caller has their own websocket to connected to an agent?我如何实现 nexmo 以便每个调用者都有自己的 websocket 连接到代理? I believe socket.io is the solution, however I'm unfamiliar with it.我相信 socket.io 是解决方案,但我不熟悉它。

const express = require('express')
const app = express()
var bodyParser = require('body-parser');
app.use(bodyParser.json());
var expressWs = require('express-ws')(app);
var isBuffer = require('is-buffer')
var header = require("waveheader");
var fs = require('fs');
var file;



//Serve a Main Page
app.get('/', function(req, res) {
    res.send("Node Websocket");
});


//Serve the NCCO on the /ncco answer URL
app.get('/ncco', function(req, res) {

    var ncco = require('./ncco.json');
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(ncco), 'utf-8');
});


//Log the Events
app.post('/event', function(req, res) {
    console.log(req.body);
    res.send("ok");
});

// Handle the Websocket
app.ws('/socket', function(ws, req) {
    var rawarray = []; 
    console.log("Websocket Connected")
    ws.on('message', function(msg) {
     if (isBuffer(msg)) {
             rawarray.push(msg);
     }
     else {
         console.log(msg); 
     }
    });
    ws.on('close', function(){
      console.log("Websocket Closed")
      file = fs.createWriteStream('./output.wav');
      file.write(header(16000 * rawarray.length/50 * 2,{
                        sampleRate: 16000,
                        channels: 1,
                        bitDepth: 16}));
      rawarray.forEach(function(data){
          file.write(data);
      });
  })
});

app.listen(8000, () => console.log('App listening on port 8000!'))

It should work with your current implementation, you'd need to do a few changes.它应该适用于您当前的实现,您需要做一些更改。 So instead of every WebSocket going in the same endpoint, and writing to the same output file, you'd need to stream each WebSocket on a separate route, and save each output to different files.因此,不是每个 WebSocket 都进入同一个端点并写入相同的输出文件,您需要在单独的路由上流式传输每个 WebSocket,并将每个输出保存到不同的文件。 Change your socket route to look like this:将您的套接字路由更改为如下所示:

app.ws('/socket/:identifier', function(ws, req) {
    var rawarray = []; 
    console.log("Websocket Connected")
    ws.on('message', function(msg) {
     if (isBuffer(msg)) {
             rawarray.push(msg);
     }
     else {
         console.log(msg); 
     }
    });
    ws.on('close', function(){
      console.log("Websocket Closed")
      file = fs.createWriteStream('./' + req.params.identifier + '.wav');
      file.write(header(16000 * rawarray.length/50 * 2,{
                        sampleRate: 16000,
                        channels: 1,
                        bitDepth: 16}));
      rawarray.forEach(function(data){
          file.write(data);
      });
  })
});

To make this work, you'd need to change your NCCO as well, instead of a static file read from disk, generate it in the route.为了使这项工作,您还需要更改您的 NCCO,而不是从磁盘读取静态文件,在路由中生成它。 I don't know what exactly you have in the file, but you can use it as is and change the socket connection bit to something like:我不知道您在文件中到底有什么,但是您可以按原样使用它并将套接字连接位更改为类似的内容:

app.get('/ncco', function(req, res) {

  var ncco = [
    {
      "action": "talk",
      "text": "Please wait while we connect you"
    },
    {
      "action": "connect",
      "eventUrl": [
        "https://yourserver.com/event"
      ],
      "from": "YOUR_NEXMO_NUMBER",
      "endpoint": [
        {
          "type": "websocket",
          "uri": "ws://yourserver.com/socket/" + req.query.from,
          "content-type": "audio/l16;rate=16000"
        }
      ]
    }
  ]
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(ncco), 'utf-8');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM