(也可以看看:如何在服务器端发送和接收 WebSocket 消息?)
这相当简单,但理解格式很重要。
第一个字节几乎总是1000 0001
,其中1
意思是“最后一帧”,三个0
s 是保留位,到目前为止没有任何意义,并且0001
意味着它是一个文本框架(Chrome 使用ws.send()
方法)。
(Update:Chrome 现在还可以发送二进制帧ArrayBuffer
。第一个字节的最后四位将是0002
,因此您可以区分文本和二进制数据。数据解码的工作方式完全相同。)
第二个字节包含一个1
(意味着它被“屏蔽”(编码))后面跟着代表帧大小的七位。如果是介于000 0000
and 111 1101
,这就是尺寸。如果它是111 1110
,接下来的 2 个字节是长度(因为它不适合 7 位),如果是111 1111
,接下来的 8 个字节是长度(如果两个字节也放不下)。
接下来是四个字节,它们是解码帧数据所需的“掩码”。这是使用 xor 编码完成的,该编码使用由以下定义的掩码之一indexOfByteInData mod 4
的数据。解码就像encodedByte xor maskByte
(where maskByte
is indexOfByteInData mod 4
).
现在我必须说我根本没有使用 C# 的经验,但这是一些伪代码(我担心有些 JavaScript 口音):
var length_code = bytes[1] & 127, // remove the first 1 by doing '& 127'
masks,
data;
if(length_code === 126) {
masks = bytes.slice(4, 8); // 'slice' returns part of the byte array
data = bytes.slice(8); // and accepts 'start' (inclusively)
} else if(length_code === 127) { // and 'end' (exclusively) as arguments
masks = bytes.slice(10, 14); // Passing no 'end' makes 'end' the length
data = bytes.slice(14); // of the array
} else {
masks = bytes.slice(2, 6);
data = bytes.slice(6);
}
// 'map' replaces each element in the array as per a specified function
// (each element will be replaced with what is returned by the function)
// The passed function accepts the value and index of the element as its
// arguments
var decoded = data.map(function(byte, index) { // index === 0 for the first byte
return byte ^ masks[ index % 4 ]; // of 'data', not of 'bytes'
// xor mod
});
您还可以下载规格这可能会有所帮助(当然它包含理解格式所需的所有内容)。