This question already has answers here:
Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

(12个答案)


4年前关闭。




我想使用ws处理从客户端收到的ArrayBuffer消息。在客户端,由于 ws.binaryType ,我直接收到ArrayBuffer,但是在服务器端,我没有收到ArrayBuffer,而是类似以下内容(字符串?):'>。

服务器如何接收ArrayBuffer?

客户端 :
var ws = new WebSocket("ws://localhost:3000/");
ws.binaryType = 'arraybuffer';
ws.onopen = function() {
    var buffer = new ArrayBuffer(15);
    var dv = new DataView(buffer);
    dv.setInt16(1, 42);
    ws.send(buffer);
};

服务器端 :
var express = require('express'),
app = express(),
server = require('http').createServer(),
WebSocketServer = require('ws').Server,
wss = new WebSocketServer({
    server: server
});

...

wss.on('connection', function(socket) {
    console.log(message);
    //log : <Buffer 00 00 2a 00 00 00 00 00 00 00 00 00 00 00 00 00>


    socket.on('message', function(message) {

        //would like to read and handle the arraybuffer properly

    });
});

最佳答案

刚要convert the Buffer to an ArrayBuffer

var buf = new Uint8Array(message).buffer;
var dv = new DataView(buf);

关于javascript - 在WebSocket(ws)上接收ArrayBuffer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39174139/

10-11 11:08