C# WiFi多线程收发报文

网络通信

public class NetClient
    {
        /// <summary>
        /// 接收数据缓冲区大小64K
        /// </summary>
        public const int DefaultBufferSize = 64 * 1024;

        public event EventHandler<EventArgCollection.ConnectionEventArgs> OnConnectionChanged;

        public event EventHandler<EventArgCollection.SocketEventArgs> OnSocketEventRaised;

        public event EventHandler<EventArgCollection.SocketErrorEventArgs> OnSocketErrorRaised;

        #region 字段

        /// <summary>
        /// 客户端与服务器之间的会话类
        /// </summary>
        private Session _session;

        /// <summary>
        /// 客户端是否已经连接服务器
        /// </summary>
        private bool _isConnected = false;

        /// <summary>
        /// 报文解析器
        /// </summary>
        private DatagramResolver _resolver;

        /// <summary>
        /// 通讯格式编码解码器
        /// </summary>
        private Coder _coder;

        /// <summary>
        /// 接收数据缓冲区
        /// </summary>
        private byte[] _recvDataBuffer = new byte[DefaultBufferSize];

        #endregion

        #region 事件定义

        /// <summary>
        /// 已经连接服务器事件
        /// </summary>
        public event NetEvent ConnectedServer;

        /// <summary>
        /// 接收到数据报文事件
        /// </summary>
        public event NetEvent ReceivedDatagram;

        /// <summary>
        /// 连接断开事件
        /// </summary>
        public event NetEvent DisConnectedServer;

        #endregion

        #region 属性

        /// <summary>
        /// 返回客户端与服务器之间的会话对象
        /// </summary>
        public Session ClientSession
        {
            get
            {
                return _session;
            }
        }

        /// <summary>
        /// 返回客户端与服务器之间的连接状态
        /// </summary>
        public bool IsConnected
        {
            get
            {
                return _isConnected;
            }
        }

        /// <summary>
        /// 数据报文分析器
        /// </summary>
        public DatagramResolver Resovlver
        {
            get
            {
                return _resolver;
            }
            set
            {
                _resolver = value;
            }
        }

        /// <summary>
        /// 编码解码器
        /// </summary>
        public Coder ServerCoder
        {
            get
            {
                return _coder;
            }
        }

        #endregion

        #region 公有方法

        /// <summary>
        /// 默认构造函数,使用默认的编码格式
        /// </summary>
        public NetClient()
        {
            _coder = new Coder(Coder.EncodingMothord.Default);
        }

        /// <summary>
        /// 构造函数,使用一个特定的编码器来初始化
        /// </summary>
        /// <param name="_coder">报文编码器</param>
        public NetClient(Coder coder)
        {
            _coder = coder;
        }

        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="ip">服务器IP地址</param>
        /// <param name="port">服务器端口</param>
        public virtual void Connect(string ip, int port)
        {
            /*
            if (IsConnected)
            {
                Debug.Assert(_session != null);
                Close();
            }
            */

            Socket newClientSocket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

            try
            {

                IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ip), port);
                newClientSocket.BeginConnect(iep, new AsyncCallback(Connected), newClientSocket);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public virtual void Disconnect()
        {

        }


        /// <summary>
        /// 发送数据报文
        /// </summary>
        /// <param name="datagram"></param>
        public virtual void Send(string datagram)
        {
            if (datagram.Length == 0)
            {
                return;
            }

            if (!_isConnected)
            {
                throw (new ApplicationException("没有连接服务器,不能发送数据"));
            }

            //获得报文的编码字节
            byte[] data = _coder.GetEncodingBytes(datagram);

            _session.ClientSocket.BeginSend(data, 0, data.Length, SocketFlags.None,
             new AsyncCallback(SendDataEnd), _session.ClientSocket);
        }

        /// <summary>
        /// 发送数据报文
        /// </summary>
        /// <param name="dataBytes"></param>
        public virtual void SendBytes(byte[] dataBytes)
        {
            if (dataBytes.Length == 0)
            {
                return;
            }

            if (!_isConnected)
            {
                throw (new ApplicationException("没有连接服务器,不能发送数据"));
            }

            //获得报文的编码字节
            byte[] data = _coder.GetEncodingBytes(dataBytes, _resolver);

            _session.ClientSocket.BeginSend(data, 0, data.Length, SocketFlags.None,
             new AsyncCallback(SendDataEnd), _session.ClientSocket);
        }


        #endregion

        #region 受保护方法

        /// <summary>
        /// 数据发送完成处理函数
        /// </summary>
        /// <param name="iar"></param>
        protected virtual void SendDataEnd(IAsyncResult iar)
        {
            Socket remoteSocket = (Socket)iar.AsyncState;
            int sent = remoteSocket.EndSend(iar);
            //Debug.Assert(sent != 0);
        }

        /// <summary>
        /// 建立Tcp连接后处理过程
        /// </summary>
        /// <param name="iar">异步Socket</param>
        protected virtual void Connected(IAsyncResult iar)
        {
            Socket cliectSocket = (Socket)iar.AsyncState;
            try
            {
                cliectSocket.EndConnect(iar);

                //创建新的会话
                _session = new Session(cliectSocket);
                _isConnected = true;


                SetConnection(_isConnected);
                //触发连接建立事件
                if (ConnectedServer != null)
                {
                    ConnectedServer(this, new NetEventArgs(_session));
                }

                _session.ClientSocket.BeginReceive(_recvDataBuffer, 0,
                 DefaultBufferSize, SocketFlags.None,
                 new AsyncCallback(ReceiveData), cliectSocket);

                Mark(string.Format("连接成功"));

            }
            catch
            {
                //throw new Exception(ex.Message);
                //_isConnected = false;
                WriteLog(sex, sex.ErrorCode.ToString());
                //SetConnection(_isConnected);
            }
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        public virtual void Close()
        {
            if (!_isConnected)
            {
                return;
            }

            _session.Close();
            _session = null;
            _isConnected = false;
        }

        public virtual void SetConnection(bool IsConnected)
        {
            //if (!IsConnected && cliectSocket != null)
            //{
            //    state.IsReceiveThreadAlive = false;

            //    try
            //    {
            //        if (statelst.Contains(state))
            //            statelst.Remove(state);

            //        state.workSocket.Shutdown(SocketShutdown.Both);
            //        state.workSocket.Close();
            //    }
            //    catch (Exception Ex)
            //    {
            //        //WriteLog(Ex, "When release socket connection.");
            //    }
            //}

            if (OnConnectionChanged != null)
                OnConnectionChanged(this, new EventArgCollection.ConnectionEventArgs() { IsConnected = IsConnected });
        }

        public void Mark(string s)
        {
            var Id = System.Threading.Thread.CurrentThread.ManagedThreadId;

            if (OnSocketEventRaised != null)
                OnSocketEventRaised(null, new EventArgCollection.SocketEventArgs() { Msg = string.Format("[线程ID:{0}] {1}", Id, s) });
        }

        public void WriteLog(Exception exp, string msg)
        {
            if (OnSocketErrorRaised != null)
                OnSocketErrorRaised(exp.Message, new EventArgCollection.SocketErrorEventArgs() { Exp = exp, Msg = msg });
        }


        /// <summary>
        /// 数据接收处理函数
        /// </summary>
        /// <param name="iar">异步Socket</param>
        protected virtual void ReceiveData(IAsyncResult iar)
        {
            Socket remote = (Socket)iar.AsyncState;
            try
            {
                int recv = remote.EndReceive(iar);
                if (recv == 0)
                {
                    _session.TypeOfExit = Session.ExitType.NormalExit;
                    if (DisConnectedServer != null)
                    {
                        DisConnectedServer(this, new NetEventArgs(_session));
                    }
                    return;
                }

                byte[] receiveDataBytes = _coder.GetDecodingBytes(_recvDataBuffer, recv);

                //ConcurrentDictionary<int, byte[]> dic = new ConcurrentDictionary<int, byte[]>();  

                //string receivedData = _coder.GetEncodingString(_recvDataBuffer, recv);

                //通过事件发布收到的报文
                if (ReceivedDatagram != null)
                {
                    ICloneable copySession = (ICloneable)_session;
                    Session clientSession = (Session)copySession.Clone();
                    clientSession.RecvDataBuffer = new byte[receiveDataBytes.Length];

                    Array.ConstrainedCopy(receiveDataBytes, 0, clientSession.RecvDataBuffer, 0, receiveDataBytes.Length);
                    //clientSession.Datagram = newDatagram;

                    //发布一个报文消息
                    ReceivedDatagram(this, new NetEventArgs(clientSession));

                    if (_resolver != null)
                    {
                        //if (_session.Datagram != null && _session.Datagram.Length != 0)
                        //{
                        //    receivedData = _session.Datagram + receivedData;
                        //}

                        //string[] recvDatagrams = _resolver.Resolve(ref receivedData);
                        //foreach (string newDatagram in recvDatagrams)
                        //{
                        //    ICloneable copySession = (ICloneable)_session;
                        //    Session clientSession = (Session)copySession.Clone();
                        //    clientSession.Datagram = newDatagram;

                        //    //发布一个报文消息
                        //    ReceivedDatagram(this, new NetEventArgs(clientSession));
                        //}

                        剩余的代码片断,下次接收的时候使用
                        //_session.Datagram = receivedData;
                    }
                    else
                    {
                        //ICloneable copySession = (ICloneable)_session;
                        //Session clientSession = (Session)copySession.Clone();
                        //clientSession.Datagram = receivedData;

                        //ReceivedDatagram(this, new NetEventArgs(clientSession));
                    }

                }//end of if(ReceivedDatagram != null)

                //继续接收数据
                _session.ClientSocket.BeginReceive(_recvDataBuffer, 0, DefaultBufferSize, SocketFlags.None,
                 new AsyncCallback(ReceiveData), _session.ClientSocket);
            }
            catch (SocketException ex)
            {
                //主机端退出
                if (10054 == ex.ErrorCode)
                {
                    _session.TypeOfExit = Session.ExitType.ExceptionExit;

                    if (DisConnectedServer != null)
                    {
                        DisConnectedServer(this, new NetEventArgs(_session));
                    }
                    //_isConnected = false;
                    //WriteLog(ex, ex.ErrorCode.ToString());
                }
                else
                {
                    //throw (ex);

                }

            }
            catch (ObjectDisposedException ex)
            {
                if (ex != null)
                {
                    ex = null;
                    //DoNothing;
                }
                //_isConnected = false;
            }
        }

        #endregion
    }

事件参数设定

public class EventArgCollection
    {
        /// <summary>
        /// ConnectionEventArgs
        /// </summary>
        public class ConnectionEventArgs : EventArgs
        {
            public bool IsConnected { get; set; }
        }

        /// <summary>
        /// SocketEventArgs
        /// </summary>
        public class SocketEventArgs : EventArgs
        {
            /// <summary>
            /// ClientName
            /// </summary>
            public string ClientName { get; set; }

            /// <summary>
            /// IsConnect
            /// </summary>
            public bool IsConnect { get; set; }

            /// <summary>
            /// Message
            /// </summary>
            public string Msg { get; set; }
        }

        /// <summary>
        /// ErrorEventArgs
        /// </summary>
        public class SocketErrorEventArgs : EventArgs
        {
            /// <summary>
            /// Exception
            /// </summary>
            public Exception Exp { get; set; }
            /// <summary>
            /// Message
            /// </summary>
            public string Msg { get; set; }
        }
    }
    /// <summary> 
    /// 网络通讯事件模型委托 
    /// </summary> 
    public delegate void NetEvent(object sender, NetEventArgs e);

连接处理通用

public class Transmitter_Network
    {
        public byte[] m_HeadBytes = new byte[4] { 0xfa, 0xfb, 0xfc, 0xfd };    //字头信息

        #region ** 内部私有变量 **

        NetClient m_NetClient;
        private bool _isConnected = false;
        #endregion

        #region ** 构造函数 **
        public Transmitter_Network()
        {
            _ThreadIsWork = true;
            _ThreadIsPause = false;
            CreateWorkThread();

            _ThreadIsWork_Send = true;
            _ThreadIsPause_Send = false;
            CreateWorkThread_Send();

            NetInitializeComponent();
        }

        #endregion

        #region ** 数据传输 **

        private void NetInitializeComponent()
        {
            m_NetClient = new NetClient(new Coder(Coder.EncodingMothord.Default));

            //m_NetClient.Resovlver=new DatagramResolver("]}");

            m_NetClient.Resovlver = new DatagramResolver(m_HeadBytes);

            m_NetClient.ReceivedDatagram += M_NetClient_ReceivedDatagram;

            m_NetClient.DisConnectedServer += M_NetClient_DisConnectedServer;

            m_NetClient.ConnectedServer += M_NetClient_ConnectedServer;

            m_NetClient.OnSocketErrorRaised += M_NetClient_OnSocketErrorRaised;

            m_NetClient.OnSocketEventRaised += M_NetClient_OnSocketEventRaised;

            //m_NetClient.Connect("192.168.1.166", 6500);
            //m_NetClient.Connect("10.10.100.254", 8899);
        }

        //public event EventHandler<EventArgCollection.ConnectionEventArgs> OnConnectionChanged;

        public event EventHandler<EventArgCollection.SocketEventArgs> OnSocketEventRaised;

        public event EventHandler<EventArgCollection.SocketErrorEventArgs> OnSocketErrorRaised;

        private void M_NetClient_OnSocketEventRaised(object sender, EventArgCollection.SocketEventArgs e)
        {
            //throw new NotImplementedException();
            if (OnSocketEventRaised != null)
                OnSocketEventRaised(null, new EventArgCollection.SocketEventArgs() { Msg = string.Format("[线程ID:{0}] {1}", "", e.Msg) });
        }

        private void M_NetClient_OnSocketErrorRaised(object sender, EventArgCollection.SocketErrorEventArgs e)
        {
            //throw new NotImplementedException();
            if (OnSocketErrorRaised != null)
                OnSocketErrorRaised(e.Exp.Message, new EventArgCollection.SocketErrorEventArgs() { Exp = e.Exp, Msg = e.Msg });
        }

        private void M_NetClient_ConnectedServer(object sender, NetEventArgs e)
        {
            //throw new NotImplementedException();
            string info = string.Format("A Client:{0} connect server :{1}", e.ClientSession,
             e.ClientSession.ClientSocket.RemoteEndPoint.ToString());

        }

        private void M_NetClient_DisConnectedServer(object sender, NetEventArgs e)
        {
            //throw new NotImplementedException();
            string info;

            if (e.ClientSession.TypeOfExit == Session.ExitType.ExceptionExit)
            {
                info = string.Format("A Client Session:{0} Exception Closed.",
                 e.ClientSession.ID);
            }
            else
            {
                info = string.Format("A Client Session:{0} Normal Closed.",
                 e.ClientSession.ID);
            }
        }
        DateTime time_Main0 = DateTime.Now;
        TimeSpan timeSpan_Main = new TimeSpan(0, 0, 0, 0);
        int RDataCount = 0;
        public delegate void RuntimeUpdateEventDelegate(TimeSpan TimeSpan, int RDataCount, int WDataCount);
        public event RuntimeUpdateEventDelegate RuntimeUpdate;

        public delegate void MyReceiveDataEventDelegate(byte[] dataBytes);
        public event MyReceiveDataEventDelegate MyReceiveData;

        public delegate void MyReceiveCommandEventDelegate(byte[] dataBytes);
        public event MyReceiveCommandEventDelegate MyReceiveCommand;

        public delegate void MySendDataEventDelegate(byte[] dataBytes);
        public event MySendDataEventDelegate MySendData;
        private void M_NetClient_ReceivedDatagram(object sender, NetEventArgs e)
        {
            //throw new NotImplementedException();
            int DataByteLength = e.ClientSession.RecvDataBuffer.Length;
            byte[] ReceiveDataBytes = new byte[DataByteLength];
            Array.ConstrainedCopy(e.ClientSession.RecvDataBuffer, 0, ReceiveDataBytes, 0, DataByteLength);

            if (MyReceiveData != null)
                MyReceiveData(ReceiveDataBytes);

            WdataCount = RDataCount - WdataCount;

            RDataCount = Split_ReceiveDataBytes(ReceiveDataBytes);

            DateTime time_Main1 = DateTime.Now;
            timeSpan_Main = time_Main1.Subtract(time_Main0);
            time_Main0 = time_Main1;
            if (RuntimeUpdate != null)
                RuntimeUpdate(timeSpan_Main, RDataCount, WdataCount);

        }
        
        object obj = new object();
        private int Split_ReceiveDataBytes(byte[] ReceiveDataBytes)
        {
            int dataCount = 0;

            for (int i = 0; i < ReceiveDataBytes.Length; i++)
            {
                if (i + 4 < ReceiveDataBytes.Length)
                {
                    if (ReceiveDataBytes[i] == m_HeadBytes[0] && ReceiveDataBytes[i + 1] == m_HeadBytes[1] && ReceiveDataBytes[i + 2] == m_HeadBytes[2] && ReceiveDataBytes[i + 3] == m_HeadBytes[3])
                    {
                        //找到 
                        int dataLength = Coder.ByteToInt32(ReceiveDataBytes[i + 4]);
                        byte[] dataBytes = new byte[dataLength];
                        if (i + 5 + dataLength - 1 < ReceiveDataBytes.Length)
                        {
                            Array.ConstrainedCopy(ReceiveDataBytes, i + 5, dataBytes, 0, dataLength);
                            lock (this)
                            {
                                if (CheckDigitByte(dataBytes))
                                {
                                    //校验检测OK
                                    if (dataBytes[0] == 0x25 && dataBytes[1] == 0x01 && dataBytes[2] == 0x02)
                                    {
                                        try
                                        {
                                            receive_Q.Enqueue(dataBytes);
                                        }
                                        catch
                                        {

                                        }
                                    }
                                    else
                                    {
                                        if (MyReceiveCommand != null)
                                            MyReceiveCommand(dataBytes);
                                    }
                                }
                            }
                            //ResolveReceiveData(dataBytes);
                            i = i + 5 + dataLength - 1;
                            dataCount++;
                        }
                    }
                }
            }

            return dataCount;
        }

        /// <summary>
        /// 校验检测
        /// </summary>
        /// <param name="dataBytes"></param>
        /// <returns></returns>
        public bool CheckDigitByte(byte[] dataBytes)
        {
            if (dataBytes.Length < 2) return false;
            byte CheckDigitByte = dataBytes[dataBytes.Length - 1];
            byte dataByte = new byte();

            for (int i = 0; i < dataBytes.Length - 1; i++)
            {
                dataByte += dataBytes[i];
            }

            return dataByte == CheckDigitByte;
        }

        #endregion

        #region ** 属性 **

        public bool IsConnected
        {
            get
            {
                this._isConnected = m_NetClient.IsConnected;
                return this._isConnected;
            }
        }


        public object Dispatcher { get; private set; }

        #endregion

        #region ** 公共方法 **

        /// <summary>
        /// 模拟人连接
        /// </summary>
        public void NetworkConnect()
        {
            try
            {
                NetworkConnect("127.0.0.1", 8899);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 模拟人连接
        /// </summary>
        /// <param name="IP"></param>
        /// <param name="Port"></param>
        public void NetworkConnect(string IP, int Port)
        {
            try
            {
                m_NetClient.Connect(IP, Port);
                Thread.Sleep(100);   //等1秒
                this._isConnected = m_NetClient.IsConnected;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }

        /// <summary>
        /// 网络连接断开
        /// </summary>
        public void NetworkDisconnect()
        {
            try
            {
                m_NetClient.Disconnect();
                Thread.Sleep(100);   //等1秒
                this._isConnected = m_NetClient.IsConnected;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public void AddSendBytes(byte[] dataBytes)
        {
            try
            {
                //Cache_SendDataBytes.Add(dataBytes);
                //入队
                System.Diagnostics.Debug.WriteLine(string.Format("{0},{1}", Common.Converter.ByteConverter.ByteArrayToHexString(dataBytes), send_Q.Count));
                send_Q.Enqueue(dataBytes);
            }
            catch (Exception)
            {

                //throw;
            }
        }

        /// <summary>
        /// 发送数据到模拟人
        /// </summary>
        /// <param name="dataBytes"></param>
        private void SendBytes(byte[] dataBytes)
        {
            try
            {
                m_NetClient.SendBytes(dataBytes);

                if (MySendData != null)
                    MySendData(dataBytes);
            }
            catch
            {
                //MessageBox.Show(ex.Message, "错误");
            }
        }

        #endregion

        #region ** 读取队列数据作业线程 **

        //private List<byte[]> Cache_ReceiveDataBytes = new List<byte[]>();
        Queue receive_Q = new Queue();

        Thread WorkThread;
        AutoResetEvent WorkResetEvent = new AutoResetEvent(true);

        private bool _ThreadIsWork = false;
        private bool _ThreadIsPause = false;

        /// <summary>
        /// 创建前线程
        /// </summary>
        public void CreateWorkThread()
        {
            this.WorkThread = new Thread(new ThreadStart(this.WorkThreedFun));
            this.WorkThread.IsBackground = true;
            this.WorkThread.Start();
        }

        /// <summary>
        /// 
        /// </summary>
        public void DestroyWorkThread()
        {
            _ThreadIsWork = false;
            Thread.Sleep(100);
            WorkThread.DisableComObjectEagerCleanup();
        }

        /// <summary>
        /// 执行线程函数
        /// </summary>
        private void WorkThreedFun()
        {
            while (true)
            {
                if (!_ThreadIsWork || _ThreadIsPause)
                {
                    this.WorkResetEvent.WaitOne();
                }
                this.DoWork();

            }
        }

        //int workRunTime = 0;

        DateTime time_Main20 = DateTime.Now;
        TimeSpan timeSpan_Main2 = new TimeSpan(0, 0, 0, 0);

        public delegate void RuntimeUpdate2EventDelegate(TimeSpan TimeSpan, int DataCount);
        //public event RuntimeUpdate2EventDelegate RuntimeUpdate2;



        int WdataCount = 0;
        /// <summary>
        /// 取出数据
        /// </summary>
        private void DoWork()
        {
            while (receive_Q.Count > 0)
            {
                //出队
                byte[] dataBytes = (byte[])receive_Q.Dequeue();
                if (dataBytes != null)
                {
                    //发送数据
                    //SendBytes(dataBytes);
                    if (MyReceiveCommand != null)
                        MyReceiveCommand(dataBytes);
                }
                //小于20条快速取出
                if (receive_Q.Count < 20)
                    System.Threading.Thread.Sleep(10);
            };
        }

        private byte[] ReadCacheData()
        {
            byte[] dataBytes = new byte[0];
            //if (Cache_ReceiveDataBytes.Count >= 10)
            //{
            //    dataBytes = Cache_ReceiveDataBytes[0];
            //    Cache_ReceiveDataBytes.RemoveAt(0);
            //}

            return dataBytes;
        }


        /// <summary>
        /// 查找是否存在的字节数据
        /// </summary>
        /// <param name="byteDataArray"></param>
        /// <param name="byteData"></param>
        /// <returns></returns>
        private bool InByte(byte[] byteDataArray, byte byteData)
        {
            if (byteDataArray == null)
                return false;
            for (int i = 0; i < byteDataArray.Length; i++)
            {
                if (byteDataArray[i] == byteData)
                {
                    return true;
                }
            }
            return false;
        }

        #endregion

        #region ** 发送队列数据作业线程 **

        Queue send_Q = new Queue();

        Thread WorkThread_Send;
        AutoResetEvent WorkResetEvent_Send = new AutoResetEvent(true);

        private bool _ThreadIsWork_Send = false;
        private bool _ThreadIsPause_Send = false;

        /// <summary>
        /// 创建前线程
        /// </summary>
        public void CreateWorkThread_Send()
        {
            this.WorkThread_Send = new Thread(new ThreadStart(this.WorkThreedFun_Send));
            this.WorkThread_Send.IsBackground = true;
            this.WorkThread_Send.Start();
        }

        /// <summary>
        /// 
        /// </summary>
        public void DestroyWorkThread_Send()
        {
            _ThreadIsWork_Send = false;
            Thread.Sleep(100);
            WorkThread_Send.DisableComObjectEagerCleanup();
        }

        /// <summary>
        /// 执行线程函数
        /// </summary>
        private void WorkThreedFun_Send()
        {
            while (true)
            {
                if (!_ThreadIsWork_Send || _ThreadIsPause_Send)
                {
                    this.WorkResetEvent_Send.WaitOne();
                }
                this.DoWork_Send();

            }
        }

        //int workRunTime_Send = 0;

        DateTime time_Main20_Send = DateTime.Now;
        TimeSpan timeSpan_Main2_Send = new TimeSpan(0, 0, 0, 0);

        public delegate void RuntimeUpdate2_SendEventDelegate(TimeSpan TimeSpan, int DataCount);
        //public event RuntimeUpdate2_SendEventDelegate RuntimeUpdate2_Send;

        //int WdataCount_Send = 0;
        /// <summary>
        /// 取出数据
        /// </summary>
        private void DoWork_Send()
        {
            while (send_Q.Count > 0)
            {
                //出队
                System.Diagnostics.Debug.WriteLine(string.Format("{0}", send_Q.Count));
                byte[] dataBytes = (byte[])send_Q.Dequeue();
                System.Diagnostics.Debug.WriteLine(string.Format("{0}", Common.Converter.ByteConverter.ByteArrayToHexString(dataBytes)));
                if (dataBytes != null)
                {
                    //发送数据
                    SendBytes(dataBytes);
                }
                System.Threading.Thread.Sleep(10);
            };

        }

        private byte[] ReadCacheData_Send()
        {
            byte[] dataBytes = new byte[0];
            //if (Cache_ReceiveDataBytes.Count >= 10)
            //{
            //    dataBytes = Cache_ReceiveDataBytes[0];
            //    Cache_ReceiveDataBytes.RemoveAt(0);
            //}

            return dataBytes;
        }

        #endregion

        #region ** 私有方法 **


        #endregion
    }

调用

Transmitter_Network Transmitter_Network = new Transmitter_Network();
Transmitter_Network.NetworkConnect(Ip, Port);
if(Transmitter_Network.IsConnected)
{
    //成功
}
else
{
    //失败
}

 

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值