我想使用ws处理从客户端收到的ArrayBuffer消息。客户端,我直接收到一个ArrayBuffer感谢 ws.binaryType ,但是服务器端,我没有收到一个ArrayBuffer,但这样的东西(字符串?):'< ;缓冲区00 00 2a 00 00 00 00 00 00 00 00 00 00 00 00 00>
服务器如何接收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
});
});
答案 0 :(得分:1)
只需convert the Buffer to an ArrayBuffer
var buf = new Uint8Array(message).buffer;
var dv = new DataView(buf);