suleil1

WebSocket发送消息,大于126字节和大于65535字节的处理

网上搜了一下WebSocket的合包函数,发现不能直接使用。查了很多资料,终于弄出来了,大于65535字节的没有测试,但是小于65535的测试通过

下面是C#代码,其他代码根据此代码修改即可

public static byte[] PackData(string message) {

            byte[] contentBytes = null;

            byte[] temp = Encoding.UTF8.GetBytes(message);

            LogWrite("内容长度:" + temp.Length);

            if (temp.Length < 126) {

                contentBytes = new byte[temp.Length + 2];

                contentBytes[0] = 0x81;

                contentBytes[1] = (byte)temp.Length;

                Array.Copy(temp, 0, contentBytes, 2, temp.Length);

            } else if (temp.Length < 0xFFFF) {

                contentBytes = new byte[temp.Length + 4];

                contentBytes[0] = 0x81;

                contentBytes[1] = 126;

                contentBytes[2] = (byte)(temp.Length >>8);

                contentBytes[3] = (byte)(temp.Length & 0xFF);

                Array.Copy(temp, 0, contentBytes, 4, temp.Length);

            } else {

                contentBytes = new byte[temp.Length + 10];

                contentBytes[0] = 0x81;

                contentBytes[1] = 127;

                contentBytes[2] = 0;

                contentBytes[3] = 0;

                contentBytes[4] = 0;

                contentBytes[5] = 0;

                contentBytes[6] = (byte)(temp.Length >>24);

                contentBytes[7] = (byte)(temp.Length >>16);

                contentBytes[8] = (byte)(temp.Length >>8);

                contentBytes[9] = (byte)(temp.Length & 0xFF);

                Array.Copy(temp, 0, contentBytes, 10, temp.Length);

            }


            return contentBytes;

        }

评论

热度(1)