简体   繁体   中英

C# WebSocket Client - not working with longer strings

I wrote a few lines to send data to a WebSocket server. When sending strings shorter than 125 chars everything is cool. The other cases don't work for some reason.

Does anybody have any clue? Here's the code :)

//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();

Thank you a lot :)

Found the problem. When dumping to the stream more than one byte at once, I was supposed to revert the array.This is how the code should look like:

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM