WebSocket中的数据类型处理经验分享。
发布于 4 年前 作者 jiangna 1563 次浏览 来自 分享

应邀请,总结了一下WebSocket模块的一个问题经验分享。

首先,很多人在使用WebSocket的时候,用了网上或者其他人的代码,实际使用中则发现接收的编码存在问题,变成了文本数据,这主要原因在于很多人复制了一些诸如CSDN的分享,分享代码如下:

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

实际使用的时候,的确可以运行,但是接收时都是文本,而js侧找不到任何的参数可以设定接收为字节集。

这时候我们看下报文格式

其中opcode报文决定了数据表现,

0x0表示附加数据帧
0x1表示文本数据帧
0x2表示二进制数据帧
0x3-7暂时无定义,为以后的非控制帧保留
0x8表示连接关闭
0x9表示ping
0xA表示pong
0xB-F暂时无定义,为以后的控制帧保留

所以,网上摘抄的写的是0x81,也就是x1,代表了文本数据帧。

改成0x82,就完美解决了。

效果图:

2 回复

你好,请教一下服务端是怎么配置wss的

( ఠൠఠ )ノ牛B……我得好好补补编码的东西了……

回到顶部