【问题标题】:Reading a message length from SSLStream从 SSLStream 读取消息长度
【发布时间】:2015-02-05 19:56:01
【问题描述】:

我正在使用 SSLStream 类实现一个协议。我开始阅读这样的消息(在消息中接收 ASCII 字符):

byte [] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
     // Read the client's test message.
     bytes = sslStream.Read(buffer, 0, buffer.Length);

     // Use Decoder class to convert from bytes to UTF8 
     // in case a character spans two buffers.
     Decoder decoder = Encoding.UTF8.GetDecoder();
     char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
     decoder.GetChars(buffer, 0, bytes, chars,0);
     messageData.Append (chars);
     // Check for EOF or an empty message. 
     if (messageData.ToString().IndexOf("<EOF>") != -1)
     {
         break;
     }
} while (bytes !=0); 

但是,现在协议发生了变化,我不需要搜索消息结尾,但我需要先读取消息长度(以字符数为单位),然后读取具有接收长度的消息。我该怎么做?

【问题讨论】:

    标签: c# .net network-programming


    【解决方案1】:

    您必须使用 TLV(类型长度值)格式,或者只使用 LV。 使用前两个字节作为长度,这给出了一个短整数的大小,我想这对你的练习来说已经足够了,但是如果需要你可以使用更多的字节。所以总是读 2 个字节。收到 2 个字节后,您会得到数字(比如说它是以二进制格式发送的),然后您会读取指定数量的八位字节/字节或字符。注意字节序,肯定是小字节序。在此链接中,您可以在我的回复中看到我是如何为 Java 做的:How to read all of Inputstream in Server Socket JAVA

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      • 2014-08-03
      相关资源
      最近更新 更多