//public static bool TryRead(this Stream stream, byte[] buffer, int offset, int count, out int bytesRead) //{ // bool successful = true; // int read = 0; // try // { // read = stream.Read(buffer, offset, count); // } // catch (Exception) // { // successful = false; // } // bytesRead = read; // return successful; //} //public static bool TryWrite(this Stream stream, byte[] buffer, int offset, int count) //{ // bool successful = true; // try // { // stream.Write(buffer, offset, count); // } // catch (Exception) // { // successful = false; // } // return successful; //} /// <summary> /// 从指定的 <see cref="System.IO.Stream"/> 中读取一条消息。 /// </summary> /// <param name="stream">要读取的 <see cref="System.IO.Stream"/>。</param> /// <param name="message">读取出的消息。如果返回值不是 <see cref="Kei.KNetwork.MessageIOErrorCode.NoError"/>,则该值无效。</param> /// <returns>一个 <see cref="Kei.KNetwork.MessageIOCode"/> 值,表示读取的结果。</returns> public static MessageIOErrorCode ReadMessage(this Stream stream, out KMessage message) { byte[] buffer; KMessage km = new KMessage(); // Check magic try { buffer = new byte[8]; stream.Read(buffer, 0, 8); km.MagicNumber = BitConverter.ToUInt64(buffer, 0); if (km.MagicNumber != KMessage.Magic) { message = km; return(MessageIOErrorCode.WrongMagicNumber); } } catch (Exception) { message = km; return(MessageIOErrorCode.ReadMagicNumberFailed); } // Read header try { var headerSize = Marshal.SizeOf(typeof(KMessageHeader)); buffer = new byte[headerSize]; stream.Read(buffer, 0, headerSize); km.Header = KMessageHeader.FromByteArray(buffer); } catch (Exception) { message = km; return(MessageIOErrorCode.ReadHeaderFailed); } // Read content try { KMessageContent content = new KMessageContent(); buffer = new byte[4]; stream.Read(buffer, 0, 4); content.DataLength = BitConverter.ToUInt32(buffer, 0); content.Data = new byte[content.DataLength]; if (content.DataLength > 0) { stream.Read(content.Data, 0, (int)content.DataLength); } km.Content = content; } catch (Exception) { message = km; return(MessageIOErrorCode.ReadContentFailed); } message = km; return(MessageIOErrorCode.NoError); }
/// <summary> /// 创建一个新的 <see cref="Kei.KNetwork.KMessageHeader"/>。 /// </summary> /// <returns>一个标准的 <see cref="Kei.KNetwork.KMessageHeader"/>。</returns> public static KMessageHeader Create() { KMessageHeader header = new KMessageHeader(); header.HeaderLength = (uint)Marshal.SizeOf(typeof(KMessageHeader)); header.HeaderVersion = 0x0001; return(header); }
/// <summary> /// 使用默认参数创建一个 <see cref="Kei.KNetwork.KMessage"/>。 /// <para>注意,直接通过该方法创建的消息是没有任何意义的。要创建有意义的消息,请使用 <see cref="Kei.KNetwork.MessageFactory"/> 类。</para> /// </summary> /// <returns></returns> internal static KMessage CreateEmptyMessage() { KMessage message = new KMessage(); message.MagicNumber = Magic; message.Header = KMessageHeader.Create(); message.Content = KMessageContent.Empty; return(message); }