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;
        }
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值