在JavaScript中解码WebSocket框架

时间:2019-04-05 18:58:26

标签: javascript websocket

我正在使用Node.js Websocket服务器,尝试将由angular发送的Websocket帧解码为客户端,但将随机字符附加到发送的数据上,

这是解码功能

function compileBuffer(buff, start, end) {
  console.log(buff);
  var message = buff.slice(start, end);
  var FIN = message[0] & 0x80;
  var RSV1 = message[0] & 0x40;
  var RSV2 = message[0] & 0x20;
  var RSV3 = message[0] & 0x10;
  var Opcode = message[0] & 0x0f;
  var mask = message[1] & 0x80;
  var length = message[1] & 0x7f;

  var nextByte = 2;
  if (length === 126) {
    // length = next 2 bytes
    nextByte += 2;
  } else if (length === 127) {
    // length = next 8 bytes
    nextByte += 8;
  }

  var maskingKey = null;
  if (mask) {
    maskingKey = message.slice(nextByte, nextByte + 4);
    nextByte += 4;
  }

  var payload = message.slice(nextByte, nextByte + length);

  if (maskingKey) {
    for (var i = 0; i < payload.length; i++) {
      payload[i] = payload[i] ^ maskingKey[i % 4];
    }
  }
  FinialData = payload.toString();
  return FinialData;
}

我发送的数据

{"username":"As123","password":"sdwA213"}

解码后的数据

){"username":"As123","password":"sdwA213"}

0 个答案:

没有答案