如何通过WebSocket从Node.js将二进制数据发送到网页?

时间:2018-05-02 14:21:27

标签: node.js websocket

我尝试过几种不同的方式发送Float32Array和ArrayBuffer,但我在客户端收到的缓冲区似乎总是空的。我该如何发送数据?我该如何访问它?

这是我最近的尝试:

server.js

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8000 });

wss.on('connection', function connection(ws) {

    var arr1 = new Float32Array(4);
    for (var i = 0; i < arr1.length; ++i)
        arr1[i] = (i + 100) / 7;

//    ws.send(arr1.buffer);


    var arr2 = new ArrayBuffer(8);
    for(var i = 0; i < 8; i++)
        arr2[i] = i * 17;

    ws.send(arr2);    
});

client.html

<!DOCTYPE html>
<html>
<head></head>
<body>

<script>

var gData = null;

var ws = new WebSocket("ws://192.168.0.7:8000");
ws.binaryType = 'arraybuffer';

ws.onmessage = function(message) {
    console.log(message.data);
    gData = message.data;
};

</script>

</body>
</html>

控制台输出

ArrayBuffer(8) {}

另外,仅仅因为我很好奇,如何将二进制数据发送回服务器?

2 个答案:

答案 0 :(得分:1)

您需要创建 WebSocket 并将其类型设置为 arraybuffer (binaryType = 'arraybuffer')。我想你在服务器端忘记了这一点。

在这个例子中,字节是从 base64 字符串信息中获取的。

    // https://stackoverflow.com/questions/21797299/convert-base64-string-to-arraybuffer
    function base64ToArrayBuffer(base64) {
        var binary_string = Buffer.from(base64, 'base64').toString('binary');
        var len = binary_string.length;
        var bytes = new Uint8Array(len);
        for (var i = 0; i < len; i++) {
            bytes[i] = binary_string.charCodeAt(i);
        }    

        return bytes.buffer;
    }

    // websocket server
    const WebSocket = require("ws"); // websocket server
    const wss = new WebSocket.Server({ port: 8082 });
    console.log("WebSocket Server Started on port 8082");

    wss.binaryType = 'arraybuffer';
    const content_base64 = "c3RyZWFtIGV2ZW50"; // Place your base64 content here.
    const binaryData = base64ToArrayBuffer(content_base64);

    wss.on("connection", (ws) => {
        console.log("WebSocket sending msg");
        ws.send(binaryData);
    });

不要忘记通过命令安装npm websocket模块:

$ npm install websocket

答案 1 :(得分:0)

ArrayBuffer它只是一个缓冲区,为了访问缓冲区中包含的内存,你需要使用view

var arr2 = new ArrayBuffer(8);
var view = new Uint8Array(arr2);
for(var i = 0; i < 8; i++)
    view[i] = i * 17;
ws.send(arr2);