Пример #1
0
        /// <summary>
        /// 读取字符串
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string ReadString(this Stream stream)
        {
            // read and check the length
            var lengthBytes = new byte[2];
            var bytesRead   = stream.Read(lengthBytes, 0, 2);

            if (bytesRead < 2)
            {
                throw new ArgumentException("The stream did not have enough bytes to describe the length of the string", "stringStream");
            }

            var enc          = new MqttEncoding();
            var stringLength = (ushort)enc.GetCharCount(lengthBytes);

            // read the bytes from the string, validate we have enough etc.
            var stringBytes = new byte[stringLength];
            var readBuffer  = new byte[1 << 10]; // 1KB read buffer
            var totalRead   = 0;

            // Keep reading until we have all. Intentionally synchronous
            while (totalRead < stringLength)
            {
                var remainingBytes = stringLength - totalRead;
                var nextReadSize   = remainingBytes > readBuffer.Length ? readBuffer.Length : remainingBytes;
                bytesRead = stream.Read(readBuffer, 0, nextReadSize);
                Array.Copy(readBuffer, 0, stringBytes, totalRead, bytesRead);
                totalRead += bytesRead;
            }

            return(enc.GetString(stringBytes));
        }
Пример #2
0
        /// <summary>
        /// 写入字符串
        /// </summary>
        /// <param name="stream">The stream containing the string to write.</param>
        /// <param name="value">The string to write.</param>
        public static void WriteString(this Stream stream, string value)
        {
            Encoding enc = new MqttEncoding();

            byte[] stringBytes = enc.GetBytes(value);
            stream.Write(stringBytes, 0, stringBytes.Length);
        }