以后端传送threejs中的点阵数组为例:
后端:
let buffer = Buffer.alloc((points.length + 4) * 4) //points.length + 4:预留前四个数字为其他信息(比如两个数字为一组,或者三个数字为一组) //预留位置 buffer.writeFloatLE(1, 0) buffer.writeFloatLE(2, 4) buffer.writeFloatLE(3, 8) buffer.writeFloatLE(4, 12) //buffer前四个数为信息 //point数据从第16位开始写入 for (let i = 0, len = points.length; i < len; i++) { buffer.writeFloatLE(points[i], i * 4 + 16) } res.send(buffer)
前端:
let pointXhr = new XMLHttpRequest() pointXhr.onreadystatechange = function () { var DONE = pointXhr.DONE || 4; if (pointXhr.readyState === DONE) { let buffer = pointXhr.response let bufferArray = new Float32Array(buffer); for (var i = 0; i < buffer.length; ++i) { bufferArray[i] = buffer[i]; } let pointsArray = bufferArray.slice(4) let points = [] //pointsArray 点阵从第5个开始(前四个数为其他信息) for (let i = 0, l = pointsArray.length / 3; i < l; i++) { points.push({ x: pointsArray[i * 3], y: pointsArray[i * 3 + 1], z: pointsArray[i * 3 + 2] }) } callback(points) } } pointXhr.open("POST",url,true); pointXhr.responseType = 'arraybuffer'; pointXhr.send(null);
前端接收图片buffer
let imageXhr = new XMLHttpRequest() imageXhr.onreadystatechange = function () { var DONE = imageXhr.DONE || 4; if (imageXhr.readyState === DONE) { if (imageXhr.response) { let bufferArray = imageXhr.response let uint8Array = new Uint8Array(bufferArray); for (var i = 0; i < bufferArray.length; ++i) { uint8Array[i] = bufferArray[i]; } callback(uint8Array) } } } imageXhr.open("POST",url,true); imageXhr.responseType = 'arraybuffer'; imageXhr.send(null);