123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace MSHO.Collection.Service.IO
- {
- public class Message
- {
- public Message() { }
- public Message(Msg msg) {
- this.Content = JsonSerializable.ToJson(msg);
- }
- public Encoding Encoding {
- get { return Encoding.UTF8; }
- }
- public long Length {
- get {
- if (this.Stream != null) {
- return this.Stream.Length;
- }
- return 0;
- }
- }
- public System.IO.MemoryStream Stream { get; set; }
- /// <summary>
- /// 错误的消息
- /// </summary>
- public bool BadMsg { get; set; }
- public string Content {
- get {
- if (this.Stream != null)
- {
- return this.Encoding.GetString(this.Stream.ToArray());
- }
- return null;
- }
- set {
- if (value != null)
- {
- var buffer = this.Encoding.GetBytes(value);
- if (this.Stream == null) { this.Stream = new System.IO.MemoryStream(); }
- this.Stream.Write(buffer, 0, buffer.Length);
- }
- else {
- this.Stream = null;
- }
- }
- }
- public byte[] ToBuffer()
- {
- var mem = new System.IO.MemoryStream();
- var buffer = Helper.LongToBytes(this.Length);
- mem.Write(buffer, 0, buffer.Length);
- if (!string.IsNullOrEmpty(this.Content))
- {
- buffer = Encoding.UTF8.GetBytes(this.Content);
- mem.Write(buffer, 0, buffer.Length);
- }
- return mem.ToArray();
- }
- public void FromStream(System.IO.MemoryStream stream) {
- if (stream != null) {
- var buffer = new byte[sizeof(long)];
- var len = stream.Read(buffer, 0, buffer.Length);
- if (len == sizeof(long)) {
- var length = Helper.BytesToLong(buffer);
- buffer = new byte[length];
- len = stream.Read(buffer, 0, (int)length);
- this.Content = this.Encoding.GetString(buffer);
- }
- }
- }
- public void Write(byte[] buffer, int pos, int size) {
- if (Stream == null) {
- Stream = new System.IO.MemoryStream();
- }
- Stream.Write(buffer, pos, size);
- }
- public void Write(byte[] buffer)
- {
- if (Stream == null)
- {
- Stream = new System.IO.MemoryStream();
- }
- Stream.Write(buffer, 0, buffer.Length);
- }
- }
-
- }
|