监控系统的一般架构之二串行数据流接口

来源:互联网 发布:淘宝店铺交易额查询 编辑:程序博客网 时间:2024/05/19 21:40

数据流接口是监控系统的的底层通讯抽象,良好的设计应当可以隔离具体的通信方式,不管你是用udp,tcp,串口还是其他的方式,只要能够实现基本的该串行数据流接口就可以了。下面是一般的串行数据流接口总结

 public interface ICommsSerial    {        // 公共方法        void Close();        void DiscardInBuffer();        void Open();        int Read(byte[] buffer, int offset, int count);        int ReadByte();        int ReadChar();        string ReadExisting();        string ReadLine();        void Write(string text);        void Write(byte[] buffer, int offset, int count);        void WriteLine(string text);        // 属性        int BytesToRead { get; }        int BytesToWrite { get; }        bool IsOpen { get; }        string PortName { get; set; }        int ReadBufferSize { get; set; }        int ReadTimeout { get; set; }        int WriteBufferSize { get; set; }        int WriteTimeout { get; set; }    }

其中的各个方法和字段都比较好理解,DiscardInBuffer方法用来丢弃当前读写缓冲器的历史数据。

下面是tcp通信的一个实现样例,你可以直接拷贝使用,也可以参照写出自己的实现。

    public class TcpSerial :  ICommsSerial, IDisposable    {        public TcpClient client = new TcpClient();        IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);        int retrys = 3;        bool reconnectnoprompt = false;        public int WriteBufferSize { get; set; }        public int WriteTimeout { get; set; }        public bool RtsEnable { get; set; }        public Stream BaseStream { get { return client.GetStream(); } }        public TcpSerial()        {            Port = "5760";        }        public string Port { get; set; }        public int ReadTimeout        {            get;// { return client.ReceiveTimeout; }            set;// { client.ReceiveTimeout = value; }        }        public int ReadBufferSize {get;set;}        public string PortName        {            get { return "TCP" + Port; }            set { }        }        public int BytesToRead        {            get { /*Console.WriteLine(DateTime.Now.Millisecond + " tcp btr " + (client.Available + rbuffer.Length - rbufferread));*/ return (int)client.Available; }        }        public int BytesToWrite { get { return 0; } }        public bool IsOpen        {            get            {                try                {                    if (client == null) return false;                    if (client.Client == null) return false;                    return client.Client.Connected;                }                catch                {                    return false;                }            }        }        public static string _host;        /// <summary>        /// 默认显示出来的了连接地址        /// </summary>        public static string Host        {            get { return _host; }            set { _host = value; }        }        public void Open(String host,String port)        {            if (client.Client.Connected)            {                log.Warn("tcpserial socket already open");                return;            }            log.Info("TCP Open");            string dest = Port;            string host = "127.0.0.1";            dest = host;            host = port;            if (!reconnectnoprompt)            {                if (System.Windows.Forms.DialogResult.Cancel == InputBox.Show("remote host", "Enter host name/ip (ensure remote end is already started)", ref host))                {                    throw new Exception("Canceled by request");                }                if (System.Windows.Forms.DialogResult.Cancel == InputBox.Show("remote Port", "Enter remote port", ref dest))                {                    throw new Exception("Canceled by request");                }            }            Port = dest;            client = new TcpClient(host, int.Parse(Port));            client.NoDelay = true;            client.Client.NoDelay = true;            VerifyConnected();            reconnectnoprompt = true;            return;        }        void VerifyConnected()        {            if (!IsOpen)            {                try                {                    client.Close();                }                catch { }                // this should only happen if we have established a connection in the first place                if (client != null && retrys > 0)                {                    log.Info("tcp reconnect");                    client.Connect(OnSettings("TCP_host", ""), int.Parse(OnSettings("TCP_port", "")));                    retrys--;                }                throw new Exception("The socket/serialproxy is closed");            }        }        public  int Read(byte[] readto,int offset,int length)        {            VerifyConnected();            try            {                if (length < 1) { return 0; }return client.Client.Receive(readto, offset, length, SocketFlags.None);/*                byte[] temp = new byte[length];                clientbuf.Read(temp, 0, length);                temp.CopyTo(readto, offset);                return length;*/            }            catch { throw new Exception("Socket Closed"); }        }        public  int ReadByte()        {            VerifyConnected();            int count = 0;            while (this.BytesToRead == 0)            {                System.Threading.Thread.Sleep(1);                if (count > ReadTimeout)                    throw new Exception("NetSerial Timeout on read");                count++;            }            byte[] buffer = new byte[1];            Read(buffer, 0, 1);            return buffer[0];        }        public  int ReadChar()        {            return ReadByte();        }        public  string ReadExisting()         {            VerifyConnected();            byte[] data = new byte[client.Available];            if (data.Length > 0)                Read(data, 0, data.Length);            string line = Encoding.ASCII.GetString(data, 0, data.Length);            return line;        }        public  void WriteLine(string line)        {            VerifyConnected();            line = line + "\n";            Write(line);        }        public  void Write(string line)        {            VerifyConnected();            byte[] data = new System.Text.ASCIIEncoding().GetBytes(line);            Write(data, 0, data.Length);        }        public  void Write(byte[] write, int offset, int length)        {            VerifyConnected();            try            {                client.Client.Send(write, length,SocketFlags.None);            }            catch { }//throw new Exception("Comport / Socket Closed"); }        }        public  void DiscardInBuffer()        {            VerifyConnected();            int size = (int)client.Available;            byte[] crap = new byte[size];            log.InfoFormat("TcpSerial DiscardInBuffer {0}",size);            Read(crap, 0, size);        }        public  string ReadLine() {            byte[] temp = new byte[4000];            int count = 0;            int timeout = 0;            while (timeout <= 100)            {                if (!this.IsOpen) { break; }                if (this.BytesToRead > 0)                {                    byte letter = (byte)this.ReadByte();                    temp[count] = letter;                    if (letter == '\n') // normal line                    {                        break;                    }                    count++;                    if (count == temp.Length)                        break;                    timeout = 0;                } else {                    timeout++;                    System.Threading.Thread.Sleep(5);                }            }            Array.Resize<byte>(ref temp, count + 1);            return Encoding.ASCII.GetString(temp, 0, temp.Length);        }        public void Close()        {            try            {                if (client.Client != null && client.Client.Connected)                {                    client.Client.Close();                    client.Close();                }            }            catch { }            try            {                client.Close();            }            catch { }            client = new TcpClient();        }        protected virtual void Dispose(bool disposing)        {            if (disposing)            {                // dispose managed resources                this.Close();                client = null;            }            // free native resources        }        public void Dispose()        {            Dispose(true);            GC.SuppressFinalize(this);        }    }


原创粉丝点击