在浏览器中接收WebSocket ArrayBuffer数据 - 改为接收字符串

时间:2013-02-23 11:39:36

标签: javascript node.js websocket arraybuffer

我有一个node.js服务器应用程序和一个浏览器客户端。发送ArrayBuffer数据浏览器 - >服务器工作得很好,但服务器 - >浏览器结果收到字符串"[object ArrayBuffer]"。这种情况发生在Chrome和Firefox的最新版本中。

服务器:

var serverPort = 9867;

// dependencies
var webSocketServer = require('websocket').server;
var http = require('http');
var players = {};
var nextPlayerId = 0;

// create http server
var server = http.createServer(function(request, response) { });
server.listen(serverPort, function() {
    console.log((new Date()) + " Server is listening on port " + serverPort);
});

// create websocket server
var wServer = new webSocketServer({ httpServer: server });
// connection request callback
wServer.on('request', function(request) {
    var connection = request.accept(null, request.origin); 
    connection.binaryType = "arraybuffer";
    var player = {};
    player.connection = connection;
    player.id = nextPlayerId;
    nextPlayerId++;
    players[player.id] = player;
    console.log((new Date()) + ' connect: ' + player.id);

    // message received callback
    connection.on('message', function(message) {
        if (message.type == 'binary' && 'binaryData' in message && message.binaryData instanceof Buffer) {
            // this works! 
            console.log('received:');
            console.log(message);   

        }
    });

    // connection closed callback
    connection.on('close', function(connection) {
        console.log((new Date()) + ' disconnect: ' + player.id);
        delete players[player.id];
    });
});

function loop() {
    var byteArray = new Uint8Array(2);
    byteArray[0] = 1;
    byteArray[0] = 2;
    for (var index in players) {
        var player = players[index];
        console.log('sending: ');
        console.log(byteArray.buffer);
        player.connection.send(byteArray.buffer);
    }
}

timerId = setInterval(loop, 500);   

客户端:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <script type="text/javascript">

      window.WebSocket = window.WebSocket || window.MozWebSocket;
      var connection = new WebSocket('ws://127.0.0.1:9867');
      connection.binaryType = "arraybuffer";

      // most important part - incoming messages
      connection.onmessage = function (event) {
        document.getElementById("log").innerHTML += typeof(event.data) + ' ';
        document.getElementById("log").innerHTML += event.data + ' ';       
        if (event.data instanceof ArrayBuffer) {
          // string received instead of a buffer
        }
      };

      window.onkeydown = function(e) {
        var byteArray = new Uint8Array(2);
        byteArray[0] = 1;
        byteArray[1] = e.keyCode;
        connection.send(byteArray.buffer);
      };
    </script>

    <div id='log'>Log: </div>
  </body>
</html>

我做错了什么?

修改

来自node.js websocket源:

WebSocketConnection.prototype.send = function(data, cb) {
    if (Buffer.isBuffer(data)) {
        this.sendBytes(data, cb);
    }
    else if (typeof(data['toString']) === 'function') {
        this.sendUTF(data, cb);
    }

因此,如果您使用Uint8Array,则会将数据作为字符串发送,而不是使用sendBytes,因为sendBytes需要Buffer个对象。如下面的答案,我需要sendBytes。由于我无法将ArrayBuffer传递给sendBytes,我在服务器上执行了此操作:

function loop() {
    var buffer = new Buffer(2);
    buffer[0] = 1;
    buffer[1] = 2;
    for (var index in players) {
        var player = players[index];
        console.log('sending: ');
        console.log(buffer);
        player.connection.send(buffer);
    }
}

现在可行。

结论:

当Chrome和Firefox网页空间.send() Uint8Array缓冲区作为二进制数据时,似乎node.js websockets将其作为string数据发送,您需要一个Buffer缓冲区发送二进制文件。

2 个答案:

答案 0 :(得分:5)

我最近一直在玩websockets,至少这似乎有用:

if(event.data instanceof ArrayBuffer)
{
  var wordarray = new Uint16Array(event.data);
  for (var i = 0; i < wordarray.length; i++) 
  {
    console.log(wordarray[i]);
    wordarray[i]=wordarray[i]+1;
  }
  console.log("End of binary message");  
  console.log("sending changes");  
  ws.send(wordarray.buffer);
}

基本上我只是基于event.data创建一个新数组

答案 1 :(得分:4)

使用sendBytes()方法发送二进制数据。