7

我有一个 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,它会将数据作为字符串发送,而不是sendBytessendBytes需要Buffer对象那样使用 。正如下面的答案,我需要sendBytes. 由于我无法传递ArrayBufferto 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 websockets.send()Uint8Array缓冲区作为二进制数据,但似乎 node.js websockets 将其作为string数据发送,并且您需要一个Buffer缓冲区来发送二进制数据。

4

2 回答 2

5

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

于 2013-02-23T12:23:02.640 回答
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 创建一个新数组

于 2013-11-19T06:52:55.093 回答