0

我写了几行代码来将数据发送到 WebSocket 服务器。当发送短于 125 个字符的字符串时,一切都很酷。其他情况由于某种原因不起作用。

有人有任何线索吗?这是代码:)

//write the first byte (FFragment + RSV1,2,3 + op-code(4-bit))
byte firstHeaderByte = 129; // 1000 0001
m_stream.WriteByte(firstHeaderByte);

if (str.Length <= 125)
{
    // the second byte is made up by 1 + 7 bit.
    // the first bit has to be 1 as a client must always use a client
    byte[] bytes = new byte[] { Convert.ToByte(str.Length + 128) };
    m_stream.Write(bytes, 0, bytes.Length);
}
else if(str.Length >= 126 && str.Length <= 65535)
{
    byte[] bytes = new byte[] { Convert.ToByte(126 + 128) };
    m_stream.Write(bytes, 0, bytes.Length);


    byte[] extendedPayLoad = BitConverter.GetBytes((short)str.Length);
    m_stream.Write(extendedPayLoad, 0, extendedPayLoad.Length);
}
else
{
    byte[] bytes = new byte[] { Convert.ToByte(127 + 128) };
    m_stream.Write(bytes, 0, bytes.Length);

    byte[] extendedPayLoad = BitConverter.GetBytes((UInt64)str.Length);
    m_stream.Write(extendedPayLoad, 0, extendedPayLoad.Length);
}


//Add the mask (4-bytes)
int maskSeed = 0;
string binaryMask = Convert.ToString(maskSeed, 2);
byte[] maskBytes = BitConverter.GetBytes(maskSeed);                
m_stream.Write(maskBytes, 0, maskBytes.Length);

//write the message
byte[] msgBytes = Encoding.UTF8.GetBytes(str);
m_stream.Write(msgBytes, 0, msgBytes.Length);

m_stream.Flush();

十分感谢 :)

4

1 回答 1

1

发现了问题。当一次转储到流中超过一个字节时,我应该恢复数组。这就是代码的样子:

var headerBytes = new List<Byte[]>();

UInt64 PayloadSize = (UInt64)payLoad.Length;
//write the first byte (FFragment + RSV1,2,3 + op-code(4-bit))
byte firstHeaderByte = 129; // 1000 0001
headerBytes.Add(new byte[] { firstHeaderByte });


if (PayloadSize <= 125)
{
    // the second byte is made up by 1 + 7 bit.
    // the first bit has to be 1 as a client must always use a client
    byte[] bytes = new byte[] { Convert.ToByte(payLoad.Length + 128) };
    Array.Reverse(bytes);
    headerBytes.Add(bytes);
}
else if (PayloadSize >= 126 && PayloadSize <= ushort.MaxValue)     
{
    var data = new byte[1];
    data[0] = 126 + 128;
    headerBytes.Add(data);

    data = BitConverter.GetBytes(Convert.ToUInt16(PayloadSize));
    Array.Reverse(data);
    headerBytes.Add(data);

}
else
{
    var data = new byte[1];
    data[0] = 127 + 128;
    headerBytes.Add(data);

    data = BitConverter.GetBytes(Convert.ToUInt64(PayloadSize));
    Array.Reverse(data);
    headerBytes.Add(data);

}
于 2013-07-30T17:06:17.760 回答