在 WebSocket 上接收 ArrayBuffer (ws)
Receive an ArrayBuffer on WebSocket (ws)
我想使用 ws 处理从客户端收到的 ArrayBuffer 消息。在客户端,由于 ws.binaryType,我直接收到了一个 ArrayBuffer,但是在服务器端,我没有收到一个 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
});
});
只好convert the Buffer to an ArrayBuffer
var buf = new Uint8Array(message).buffer;
var dv = new DataView(buf);
我想使用 ws 处理从客户端收到的 ArrayBuffer 消息。在客户端,由于 ws.binaryType,我直接收到了一个 ArrayBuffer,但是在服务器端,我没有收到一个 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
});
});
只好convert the Buffer to an ArrayBuffer
var buf = new Uint8Array(message).buffer;
var dv = new DataView(buf);