如何通过Websockets路由不同的数据类型

how to route different data types over Websockets?

本文关键字:数据类型 路由 何通过 Websockets      更新时间:2023-09-26

我必须通过websocket服务器发送大量ArrayBuffer(音频语音数据)。问题是,客户端必须知道传入数据是哪种类型的ArrayBuffer(Uint8/Uint16/Float32…)。如果用户切换到其他音频质量,该类型可能会随时更改。

向客户端通知阵列类型的最佳方式是什么?

迄今为止的想法:

  • 在数组中添加一个额外的前缀字节(这可能很慢,因为我必须为每个音频块创建一个新的arrayBuffer)
  • 使用不同的路由,如/16float或/uint8来知道哪些数据即将到来。(我没有找到任何关于如何使用websocket的信息)

有更好的方法吗?有人能给我举一个使用websocket的URL路径路由的例子吗?


编辑:我实现了前缀字节来发送有关客户端和数组类型的信息,但仍然对更好/其他的解决方案感兴趣。

Cracker0dks,为什么要使用纯websocket而不是库。有了primus,你可以使用子流名称空间——这或多或少正是你想要的——你也可以使用primus的二进制解析器。

Socket.io也是一种选择,但它们不如primus。(在我看来)

目前它是ws 最受支持/最稳定/最完整的解决方案

 // server side:
var primus
    , server
    , substream
    , http
    , Uint8
    , Uint16
    , Float32
    ;
Primus = require('primus');
http = require('http');
substream = require('substream');
server = http.createServer();
primus = new Primus(server);
primus.use('substream', substream);
server.listen(8000);
primus.on('connection', function (spark) {
    Uint8 = spark.substream('Uint8');
    Uint16 = spark.substream('Uint16');
    Float32 = spark.substream('Float32');
    Uint8.on('data', function (data) {
        console.log(data); //we recieve data from client on Uint8 ('to server') 
    });
    Uint16.on('data', function (data) {
        console.log(data); //we recieve data from client on Uint16 ('to server') 
    });
    Float32.on('data', function (data) {
        console.log(data); //we recieve data from client on Float32 ('to server') 
    });
    Uint8.write('to client'); // write data to client to Uint8
    Uint16.write('to client'); // write data to client to Uint16
    Float32.write('to client'); // write data to client to Float32
    //
    // piping data to Float32 
    //
    fs.createReadSteam(__dirname + '/example.js').pipe(Float32, {
        end: false
    });
    //
    // To stop receiving data, simply end the substream:
    //
    Uint16.end();
});


// client side:
var primus
    , Uint8
    , Uint16
    , Float32
    ;
primus = new Primus('server address');
Uint8 = primus.substream('Uint8');
Uint8.write('to server'); // write data to server to Uint8
Uint16 = primus.substream('Uint16');
Uint16.write('to server'); // write data to server to Uint16
Float32 = primus.substream('Float32');
Float32.write('to server'); // write data to server to Float32

Uint8.on('data', function (data) {
    console.log(data); // you get data from server to Uint8 ('to client') 
});
Uint16.on('data', function (data) {
    console.log(data); // you get data from server to Uint8 ('to client') 
});
Float32.on('data', function (data) {
    console.log(data); // you get data from server to Uint8 ('to client') 
});

以上内容取自他们的文档,并根据您的示例进行了更改——我没有测试它,但它应该可以工作。

我希望这能有所帮助。