Ejemplo n.º 1
0
        public void Connect()
        {
            try
            {
                log4net.Config.XmlConfigurator.Configure();
                string host = Ip;
                int    port = Convert.ToInt16(Port);
                communication                = new TcpCommunication(host, port);
                protocol                     = new HJ212Protocol();
                protocol.OnDataSend         += SendData;
                communication.OnStateChange += state =>
                {
                    if (state)
                    {
                        ConnectionColor   = "Green";
                        ConnectionContext = "断开";
                        SendTextEnable    = true;
                        protocol.BeginTask();
                    }
                    else
                    {
                        ConnectionColor   = "Red";
                        ConnectionContext = "连接";
                        SendTextEnable    = false;
                        protocol.ConnectStop();
                    }
                };

                communication.OnDataReceive += data =>
                {
                    try
                    {
                        AcceptText += "【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "】收到数据:" + data;
                        logger.Info("【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "】收到数据:" + data);
                        protocol.DataReceive(data);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                };
                communication.OnError += err =>
                {
                    logger.Error(err);
                    AcceptText       += "【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "】异常:" + err.Message;
                    ConnectionColor   = "Red";
                    ConnectionContext = "连接";
                    SendTextEnable    = false;
                    protocol.ConnectStop();
                };

                communication.Connect();
            }
            catch (Exception ex)
            {
                ConnectionColor   = "Red";
                ConnectionContext = "连接";
                SendTextEnable    = false;
                logger.Error(ex);
            }
        }