C# WebSocket decoding

620 views Asked by At

I´m trying to make a WebSocketServer in C#. In General it´s working fine, but I thing I have a problem in the decode process.

Here is my decode function:

public static byte[] EncodeMessageToSend(string message)
    {
        byte[] response;
        byte[] bytesRaw = Encoding.UTF8.GetBytes(message);
        byte[] frame = new byte[10];

        Int32 indexStartRawData = -1;
        Int32 length = bytesRaw.Length;

        frame[0] = (byte)129;
        if (length <= 125)
        {
            frame[1] = (byte)length;
            indexStartRawData = 2;
        }
        else if (length >= 126 && length <= 65535)
        {
            frame[1] = (byte)126;
            frame[2] = (byte)((length >> 8) & 255);
            frame[3] = (byte)(length & 255);
            indexStartRawData = 4;
        }
        else
        {
            frame[1] = (byte)127;
            frame[2] = (byte)((length >> 56) & 255);
            frame[3] = (byte)((length >> 48) & 255);
            frame[4] = (byte)((length >> 40) & 255);
            frame[5] = (byte)((length >> 32) & 255);
            frame[6] = (byte)((length >> 24) & 255);
            frame[7] = (byte)((length >> 16) & 255);
            frame[8] = (byte)((length >> 8) & 255);
            frame[9] = (byte)(length & 255);

            indexStartRawData = 10;
        }

        response = new byte[indexStartRawData + length];

        Int32 i, reponseIdx = 0;

        //Add the frame bytes to the reponse
        for (i = 0; i < indexStartRawData; i++)
        {
            response[reponseIdx] = frame[i];
            reponseIdx++;
        }

        //Add the data bytes to the response
        for (i = 0; i < length; i++)
        {
            response[reponseIdx] = bytesRaw[i];
            reponseIdx++;
        }

        return response;
    }

I´ve got that from this thread

Sometimes it decodes properly, but then it starts to do strange things. It appends some questionmarks or undefined characters. I´ve also tried a few other decoding function, but they didn´t worked aswell.

I hope someon can help me.

Greets Marcel

0

There are 0 answers