我写了几行代码来将数据发送到 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();
十分感谢 :)