Ejemplo n.º 1
0
        /// <summary>
        /// 注册登记
        /// 15 01 01 00 00 00 00 17 00 7b 22 44 65 76 69 63 65 49 64 22 3a 22 74 65 73 74 31 32 33 34 22 7d 5A 02
        /// </summary>
        public void Regester(BaseDataModel _baseDataModel)
        {
            baseDataModel = _baseDataModel;

            string data = "{\"DeviceId\":\"" + baseDataModel.deviceAddress + "\"}";

            sendDataMethod(data, CMDCode.Register);
            int tryTimes = 0;

            do
            {
                Thread.Sleep(500);
                if (isEnd)
                {
                    break;
                }
                if (tryTimes >= 6)
                {
                    _client.Close();
                    _log.InfoFormat("{0}{1} DustMonitoringService 设备号:{2} 服务器响应超时链接已断开", DateTime.Now, Environment.NewLine, baseDataModel.deviceAddress);
                    break;
                }
                tryTimes++;
            } while (true);

            _client.Close();
            _client.Dispose();
        }
Ejemplo n.º 2
0
        public void Disconnect()
        {
            if (!IsConnected)
            {
                return;
            }
            if (this.ConnectToEndPoint.Address.Equals(IPAddress.None) ||
                this.ConnectToEndPoint.Address.Equals(IPAddress.IPv6None))
            {
                return;
            }

            try
            {
                _client.ServerConnected    -= OnServerConnected;
                _client.ServerDisconnected -= OnServerDisconnected;
                _client.ServerDataReceived -= OnServerDataReceived;
                _client.Close();
                _client = null;
            }
            catch { }
            finally
            {
                OnDisconnect();
            }
        }
Ejemplo n.º 3
0
 private static void CloseTcpSocketClient(TcpSocketClient client)
 {
     client.ServerConnected    -= client_ServerConnected;
     client.ServerDisconnected -= client_ServerDisconnected;
     client.ServerDataReceived -= client_ServerDataReceived;
     client.Close();
 }
Ejemplo n.º 4
0
 public void Dispose()
 {
     Client.Close();
     Client.Dispose();
     Client = null;
     PollingTimer.Dispose();
     PollingTimer = null;
 }
Ejemplo n.º 5
0
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            try
            {
                AutoResetEvent  waitEvent    = new AutoResetEvent(false);
                ResponseModel   response     = null;
                TcpSocketClient socketClient = new TcpSocketClient(ServerIp, ServerPort)
                {
                    HandleRecMsg = (a, bytes) =>
                    {
                        response = bytes.ToString(Encoding.UTF8).ToObject <ResponseModel>();
                        waitEvent.Set();
                    },
                    RecLength       = 1024 * 1024,
                    HandleException = new Action <Exception>(ex => {
                        Console.WriteLine(ex.Message);
                    })
                };
                bool started = socketClient.StartClient();
                if (started)
                {
                    RequestModel requestModel = new RequestModel
                    {
                        ServiceName = ServiceName,
                        MethodName  = binder.Name,
                        Paramters   = args.ToList()
                    };
                    socketClient.Send(requestModel.ToJson().ToBytes(Encoding.UTF8));
                    waitEvent.WaitOne(new TimeSpan(0, 0, 5));
                    socketClient.Close();
                }
                else
                {
                    throw new Exception("连接到服务端失败!");
                }

                if (response == null)
                {
                    throw new Exception("服务器超时未响应");
                }
                else if (response.Success)
                {
                    result = response.Data.ToObject(ServiceType.GetMethod(binder.Name).ReturnType);
                    return(true);
                }
                else
                {
                    throw new Exception($"服务器异常,错误消息:{response.Msg}");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 噪音数据上报
        /// </summary>
        public void UploadData(BaseDataModel _baseDataModel)
        {
            RequstModel requstModel = new RequstModel();
            string      resultStr   = requstModel.ToString(new DataModel()
            {
                Humidity      = _baseDataModel.humidity,
                Noise         = _baseDataModel.noise,
                PM10          = _baseDataModel.PM10,
                PM25          = _baseDataModel.PM25,
                Temperature   = _baseDataModel.temperature,
                WindDirection = _baseDataModel.windDirection,
                WindSpeed     = _baseDataModel.windSpeed,

                TerminalNumber = _baseDataModel.deviceAddress,
                DeviceAddress  = _baseDataModel.deviceAddress
            });

            byte[] sendData = Encoding.ASCII.GetBytes(resultStr);
            tcpSend(sendData);

            int tryTimes = 0;

            do
            {
                Thread.Sleep(500);
                if (isEnd)
                {
                    break;
                }
                if (tryTimes >= 6)
                {
                    _client.Close();
                    _log.InfoFormat("{0}{1} TBJDataUploadService 设备号:{2} 服务器响应超时链接已断开", DateTime.Now, Environment.NewLine, _baseDataModel.deviceAddress);
                    break;
                }
                tryTimes++;
            } while (true);

            _log.InfoFormat("{0}{1} TBJDataUploadService 数据上传完成 设备号:{2}", DateTime.Now, Environment.NewLine, _baseDataModel.deviceAddress);
            _client.Close();
            _client.Dispose();
        }
Ejemplo n.º 7
0
        public void Connect()
        {
            if (IsConnected)
            {
                return;
            }
            if (this.ConnectToEndPoint.Address.Equals(IPAddress.None) ||
                this.ConnectToEndPoint.Address.Equals(IPAddress.IPv6None))
            {
                return;
            }

            try
            {
                var configuration = new TcpSocketClientConfiguration()
                {
                    ConnectTimeout    = this.TransportConfiguration.ConnectTimeout,
                    ReceiveBufferSize = this.TransportConfiguration.ReceiveBufferSize,
                    SendBufferSize    = this.TransportConfiguration.SendBufferSize,
                    ReceiveTimeout    = this.TransportConfiguration.ReceiveTimeout,
                    SendTimeout       = this.TransportConfiguration.SendTimeout,
                    NoDelay           = this.TransportConfiguration.NoDelay,
                    LingerState       = this.TransportConfiguration.LingerState,
                    KeepAlive         = this.TransportConfiguration.KeepAlive,
                    KeepAliveInterval = this.TransportConfiguration.KeepAliveInterval,
                    ReuseAddress      = this.TransportConfiguration.ReuseAddress,
                };
                _client = new TcpSocketClient(this.ConnectToEndPoint, configuration);
                _client.ServerConnected    += OnServerConnected;
                _client.ServerDisconnected += OnServerDisconnected;
                _client.ServerDataReceived += OnServerDataReceived;

                _log.DebugFormat("TCP client is connecting to [{0}].", this.ConnectToEndPoint);
                _client.Connect();

                OnConnect();
            }
            catch
            {
                if (_client != null)
                {
                    _client.Close();
                    _client.ServerConnected    -= OnServerConnected;
                    _client.ServerDisconnected -= OnServerDisconnected;
                    _client.ServerDataReceived -= OnServerDataReceived;
                    _client = null;
                }

                throw;
            }
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            NLogLogger.Use();

            ConnectToServer();

            Console.WriteLine("TCP client has connected to server.");
            Console.WriteLine("Type something to send to server...");
            while (true)
            {
                try
                {
                    string text = Console.ReadLine();
                    if (text == "quit")
                    {
                        break;
                    }
                    else if (text == "many")
                    {
                        text = new string('x', 8192);
                        for (int i = 0; i < 1000000; i++)
                        {
                            _client.Send(Encoding.UTF8.GetBytes(text));
                        }
                    }
                    else if (text == "big")
                    {
                        text = new string('x', 1024 * 1024 * 100);
                        _client.Send(Encoding.UTF8.GetBytes(text));
                    }
                    else
                    {
                        _client.Send(Encoding.UTF8.GetBytes(text));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            _client.Close();
            Console.WriteLine("TCP client has disconnected from server.");

            Console.ReadKey();
        }
Ejemplo n.º 9
0
        public void Connect(TimeSpan timeout)
        {
            if (IsConnected)
            {
                return;
            }
            if (this.ConnectToEndPoint.Address.Equals(IPAddress.None) ||
                this.ConnectToEndPoint.Address.Equals(IPAddress.IPv6None))
            {
                return;
            }

            try
            {
                var configuration = new TcpSocketClientConfiguration()
                {
                    ConnectTimeout = timeout,
                    SendTimeout    = TimeSpan.FromMinutes(1),
                    ReceiveTimeout = TimeSpan.Zero,
                    KeepAlive      = true,
                };
                _client = new TcpSocketClient(this.ConnectToEndPoint, configuration);
                _client.ServerConnected    += OnServerConnected;
                _client.ServerDisconnected += OnServerDisconnected;
                _client.ServerDataReceived += OnServerDataReceived;

                _log.InfoFormat("TCP client is connecting to [{0}].", this.ConnectToEndPoint);
                _client.Connect();

                OnConnect();
            }
            catch
            {
                _client.ServerConnected    -= OnServerConnected;
                _client.ServerDisconnected -= OnServerDisconnected;
                _client.ServerDataReceived -= OnServerDataReceived;
                _client.Close();
                _client = null;

                throw;
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 噪音数据上报
        ///
        //string.Format("&&DataTime={0};" +
        //        "a01001-Rtd={1},a01001-Flag=N;" +
        //        "a01002-Rtd={2},a01002-Flag=N;" +
        //        "a01006-Rtd={3},a01006-Flag=N;" +
        //        "a01007-Rtd={4},a01007-Flag=N;" +
        //        "a01008-Rtd={5},a01008-Flag=N;" +
        //        "a34001-Rtd={6},a34001-Flag=N;" +
        //        "a34002-Rtd={7},a34002-Flag=N;" +
        //        "a34004-Rtd={8},a34004-Flag=N;" +
        //        "La-Rtd={9},La-Flag=N;" +
        //        "longitude={10};latitude={11};&&",
        //                DateTime.Now.ToString("yyyyMMddhhmmss"),
        //        _baseDataModel.temperature,     //温度 摄氏度
        //        _baseDataModel.humidity,     //湿度 %
        //        0,     //气压 千帕
        //        _baseDataModel.windSpeed,     //风速 米/秒
        //        _baseDataModel.windDirection,     //风向 角度
        //        _baseDataModel.TSP,     //总悬浮颗粒物 TSP
        //        _baseDataModel.PM10,     //可吸入颗粒物 PM10
        //        _baseDataModel.PM25,     //细微颗粒物 PM2.5
        //        _baseDataModel.noise,     //噪声 分贝
        //        _baseDataModel.longitude,
        //        _baseDataModel.latitude
        //        )
        /// </summary>
        public void UploadData(BaseDataModel _baseDataModel)
        {
            RequstModel   requstModel = new RequstModel();
            StringBuilder cpsb        = new StringBuilder();

            cpsb.Append("&&").AppendFormat("DataTime={0};", DateTime.Now.ToString("yyyyMMddhhmmss"));

            if (!string.IsNullOrEmpty(_baseDataModel.temperature))//温度 摄氏度
            {
                cpsb.AppendFormat("a01001-Rtd={0},a01001-Flag=N;", _baseDataModel.temperature);
            }
            if (!string.IsNullOrEmpty(_baseDataModel.humidity))//湿度 %
            {
                cpsb.AppendFormat("a01002-Rtd={0},a01002-Flag=N;", _baseDataModel.humidity);
            }
            if (!string.IsNullOrEmpty(_baseDataModel.windSpeed))//风速 米/秒
            {
                cpsb.AppendFormat("a01007-Rtd={0},a01007-Flag=N;", _baseDataModel.windSpeed);
            }
            if (!string.IsNullOrEmpty(_baseDataModel.windDirection))//风向 角度
            {
                cpsb.AppendFormat("a01008-Rtd={0},a01008-Flag=N;", _baseDataModel.windDirection);
            }
            if (!string.IsNullOrEmpty(_baseDataModel.TSP))//总悬浮颗粒物 TSP
            {
                cpsb.AppendFormat("a34001-Rtd={0},a34001-Flag=N;", _baseDataModel.TSP);
            }
            if (!string.IsNullOrEmpty(_baseDataModel.PM10))//可吸入颗粒物 PM10
            {
                cpsb.AppendFormat("a34002-Rtd={0},a34002-Flag=N;", _baseDataModel.PM10);
            }
            if (!string.IsNullOrEmpty(_baseDataModel.PM25))//细微颗粒物 PM2.5
            {
                cpsb.AppendFormat("a34004-Rtd={0},a34004-Flag=N;", _baseDataModel.PM25);
            }
            if (!string.IsNullOrEmpty(_baseDataModel.noise))//噪声 分贝
            {
                cpsb.AppendFormat("La-Rtd={0},La-Flag=N;", _baseDataModel.noise);
            }
            if (!string.IsNullOrEmpty(_baseDataModel.longitude))//经度
            {
                cpsb.AppendFormat("longitude={0};", _baseDataModel.longitude);
            }
            if (!string.IsNullOrEmpty(_baseDataModel.latitude))//纬度
            {
                cpsb.AppendFormat("latitude={0};", _baseDataModel.latitude);
            }
            cpsb.Append("&&");

            string resultStr = requstModel.ToString(new DataModel()
            {
                QN   = DateTime.Now.ToString("yyyyMMddHHmmssfff"),
                ST   = "39",
                CN   = "2011",
                PW   = "123456",
                MN   = _baseDataModel.deviceAddress,
                Flag = "5",
                CP   = cpsb.ToString(),
            });

            byte[] sendData = Encoding.ASCII.GetBytes(resultStr);
            tcpSend(sendData);

            //do
            //{
            //    Thread.Sleep(1000);
            //    if (isEnd)
            //    {
            //        break;
            //    }
            //} while (true);

            _log.InfoFormat("{0}{1} MonitoringPollutantsTask 数据上传完成 设备号:{2}", DateTime.Now, Environment.NewLine, _baseDataModel.deviceAddress);
            _client.Close();
            _client.Dispose();
        }
Ejemplo n.º 11
0
 private static void ReconnectTcpSocketClient(TcpSocketClient client)
 {
     client.Close();
     client.Connect();
 }