我必须通过websocket服务器发送大量ArrayBuffers(音频语音数据)。问题是,客户端必须知道传入数据是哪种类型的ArrayBuffer(Uint8 / Uint16 / Float32 ...)。如果用户切换到其他音频质量,则类型可以即时更改。
告知客户端有关阵列类型的最佳方法是什么?
到目前为止的想法:
有更好的方法吗?任何人都可以举个例子说明带有websockets的URL-Path路由是如何工作的吗?
修改: 我实现了前缀字节来发送有关客户端和数组类型的信息,但仍然对更好/其他解决方案感兴趣。
答案 0 :(得分:1)
Cracker0dks,你为什么使用纯webockets而不是库?使用primus,您可以使用substream - namespace - 这或多或少完全符合您的要求 - 您也可以使用带有primus的binnary解析器。
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')
});
以上内容取自他们的文档并更改为适合您的示例 - 我没有测试它但它应该可以工作。
我希望有所帮助。