Example #1
0
        /// <summary>
        /// Adds the specified timeout action.
        /// </summary>
        /// <param name="tick">The tick.</param>
        /// <param name="exceptionHandler">the exception handler </param>
        /// <param name="timeout">The timeout.</param>
        /// <returns></returns>
        public IDisposable Add(Action tick, Action <Exception> exceptionHandler, TimeSpan timeout)
        {
            var timeoutObj = new TimeoutObject(this, tick, exceptionHandler, timeout, TimeSpan.Zero);

            this.AddInternal(timeoutObj);
            return(timeoutObj);
        }
        public ProtocolFunction(string ipstr, int port, int timeOutSec, string _key, string _simnum, System.Windows.Forms.TextBox msgBox)
        {
            IPAddress ip = IPAddress.Parse(ipstr);

            txtInfo = msgBox;
            key     = _key;
            simNum  = _simnum;
            WinFormHelper.ShowInfo(txtInfo, $"开始连接Connection");
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // clientSocket.Connect(new IPEndPoint(ip, port)); //配置服务器IP与端口
            clientSocket.BeginConnect(new IPEndPoint(ip, port), CallBackMethod, clientSocket);
            WinFormHelper.ShowInfo(txtInfo, $"Connection 正在连接......");
            //阻塞当前线程
            if (TimeoutObject.WaitOne(timeOutSec, false))
            {
                if (!clientSocket.Connected)
                {
                    WinFormHelper.ShowInfo(txtInfo, "连接服务器失败");
                    throw new Exception("socket连接失败");
                }
                WinFormHelper.ShowInfo(txtInfo, $"连接服务器成功,占用端口:{clientSocket.LocalEndPoint.ToString()}");
                isConnection = true;
            }
            else
            {
                throw new Exception("连接服务器超时了");
            }
        }
        public long CreateTimeout(Action <long, object> callback, float time, object parameter = null)
        {
            TimeoutObject timeout = new TimeoutObject(time, callback, parameter);

            _timeoutDic[timeout.ID] = timeout;
            _bWaitCheck             = true;
            return(timeout.ID);
        }
        private const int OutTimeConn = 10000; //连接时间超时  5秒

        public BaseResponse SendMessage(BaseRequest bmr, string WebsiteCode, string TellerCode)
        {
            TimeoutObject.Reset();
            BaseResponse result = null;

            _socket.BeginConnect(new IPEndPoint(IPAddress.Parse(RemoteIP), RemotePort), delegate(IAsyncResult ar) { TimeoutObject.Set(); }, _socket);
            if (TimeoutObject.WaitOne(OutTimeConn, false))
            {
                _socket.ReceiveTimeout = OutTime;
                _socket.SendTimeout    = OutTime;
                string str = bmr.ObjectToMessage();
                _socket.Send(Encod.GetBytes(str));
                len = _socket.Receive(buffer);

                if (len > 0)
                {
                    string strbuff = Encod.GetString(buffer);
                    switch (bmr.BusinessCode)
                    {
                    case "01": result = new Response01(buffer); break;

                    case "02": result = new Response02(buffer); break;

                    case "03": result = new Response03(buffer); break;

                    case "04": result = new Response04(buffer); break;

                    case "05": result = new Response05(buffer); break;

                    case "06": result = new Response06(buffer); break;

                    case "07": result = new Response07(buffer); break;

                    case "08": result = new Response08(buffer); break;

                    case "09": result = new Response09(buffer); break;

                    default: return(null);
                    }
                }
                bmr.SaveMessage(WebsiteCode, TellerCode);
                if (result != null)
                {
                    result.BankCode = bmr.BankCode;
                    result.SaveMessage(WebsiteCode, TellerCode);
                }
                return(result);
            }
            else
            {
                if (_socket.Connected)
                {
                    _socket.Shutdown(SocketShutdown.Both);
                    _socket.Close();
                }
                throw new Exception("所提供的服务器连接超时");
            }
        }
Example #5
0
        public void StartClient()
        {
            try
            {
                //1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议)
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //2.0 创建IP对象
                IPAddress address = IPAddress.Parse(_ip);
                //3.0 创建网络端口包括ip和端口
                IPEndPoint endPoint = new IPEndPoint(address, _port);
                //4.0 建立连接
                _socket.BeginConnect(endPoint, CallBackMethod, _socket);
                //阻塞当前线程

                /*if (TimeoutObject.WaitOne(1000, false))//1s超时
                 * {
                 *  MessageBox.Show("网络正常");
                 * }
                 * else
                 * {
                 *  MessageBox.Show("连接超时");
                 * }
                 * //接收返回值
                 * byte[] buffer = new byte[1024 * 1024 * 3];
                 * //实际接收到的有效字节数
                 * int FtpReturn_len = _socket.Receive(buffer);//获取buffer(int)
                 * FtpReturn_Str = Encoding.UTF8.GetString(buffer, 0, FtpReturn_len);//FTPsocket返回值,UTF8编码buffer转为string格式
                 */
                if (TimeoutObject.WaitOne(1000, false))//1s超时//StartHeck_flag为0时,破解按钮没被开启,能弹窗“网络正常”
                {
                    if (StartHeck_flag == 0)
                    {
                        MessageBox.Show("网络正常,端口开放!");
                        WriteSeachInfo(textBox1.Text);
                        WriteSeachInfo(textBox4.Text);
                    }
                    Time_Out = 0;
                }
                else
                {
                    if (StartHeck_flag == 0)
                    {
                        MessageBox.Show("连接超时");
                    }
                    Time_Out = 1;//超时标志
                }
            }
            catch (Exception ex)
            {
                // _socket.Shutdown(SocketShutdown.Both);
                _socket.Close();
                MessageBox.Show(ex.Message);//远程主机强迫关闭了一个连接/无法连接/连接失败/通讯失败
            }
            //            Thread.Sleep(2000);
            //            MessageBox.Show("发送消息结束");
        }
Example #6
0
        protected AsyncOp(string name, int timeout, model.IProxy proxy, ILog log)
        {
            Log          = log;
            Name         = name;
            Proxy        = proxy;
            TimeoutInSec = timeout;

            _timeoutObject            = new TimeoutObject(Name, timeout);
            _timeoutObject.OnTimeout += _timeoutObject_OnTimeout;
        }
Example #7
0
        protected AsyncOp(string name, int timeout, model.IProxy proxy, ILog log)
        {
            Log = log;
            Name = name;
            Proxy = proxy;
            TimeoutInSec = timeout;

            _timeoutObject = new TimeoutObject(Name, timeout);
            _timeoutObject.OnTimeout += _timeoutObject_OnTimeout;
        }
Example #8
0
        protected AsyncOp(string name, int timeout)
        {
            Name = name;
            TimeoutInSec = timeout;

            _timeoutObject = new TimeoutObject(Name, timeout);
            _timeoutObject.OnTimeout += _timeoutObject_OnTimeout;

            Log = LogManager.GetLogger(typeof(AsyncOp));
            Proxy = new model.Proxy();
        }
Example #9
0
        protected AsyncOp(string name, int timeout)
        {
            Name         = name;
            TimeoutInSec = timeout;

            _timeoutObject            = new TimeoutObject(Name, timeout);
            _timeoutObject.OnTimeout += _timeoutObject_OnTimeout;

            Log   = LogManager.GetLogger(typeof(AsyncOp));
            Proxy = new model.Proxy();
        }
Example #10
0
        /// <summary>
        /// Adds the specified repeating timeout action.
        /// </summary>
        /// <param name="tick">The tick.</param>
        /// <param name="exceptionHandler">The exception handler </param>
        /// <param name="interval">The interval.</param>
        /// <param name="initialDelay">The initial delay.</param>
        /// <returns></returns>
        public IDisposable AddRepeating(Action tick, Action <Exception> exceptionHandler, TimeSpan interval, TimeSpan initialDelay)
        {
            if (initialDelay <= TimeSpan.Zero)
            {
                initialDelay = interval;
            }

            var timeoutObj = new TimeoutObject(this, tick, exceptionHandler, initialDelay, interval);

            this.AddInternal(timeoutObj);
            return(timeoutObj);
        }
Example #11
0
        /// <summary>
        /// Removes the action and stops the thread if necessary.
        /// </summary>
        /// <param name="timeoutObj">The timeout obj.</param>
        protected virtual void RemoveInternal(TimeoutObject timeoutObj)
        {
            lock (this.TimeoutObjects)
            {
                this.TimeoutObjects.Remove(timeoutObj);
                if (this.TimeoutObjects.Count == 0)
                {
                    this.StopTimerThread();
                }

                Monitor.PulseAll(this.TimeoutObjects);
            }
        }
Example #12
0
        /// <summary>
        /// Adds the action and starts the thread if necessary.
        /// </summary>
        /// <param name="timeoutObj">The timeout obj.</param>
        protected virtual void AddInternal(TimeoutObject timeoutObj)
        {
            lock (this.TimeoutObjects)
            {
                this.TimeoutObjects.Add(timeoutObj);
                if (this.TimeoutObjects.Count == 1)
                {
                    this.StartTimerThread();
                }

                Monitor.PulseAll(this.TimeoutObjects);
            }
        }
Example #13
0
        /// <summary>
        /// 开启服务,连接服务端
        /// </summary>
        public void StartClient()
        {
            try
            {
                //1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议)
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //2.0 创建IP对象
                IPAddress address = IPAddress.Parse(_ip);
                //3.0 创建网络端口包括ip和端口
                IPEndPoint endPoint = new IPEndPoint(address, _port);
                //4.0 建立连接
                _socket.BeginConnect(endPoint, CallBackMethod, _socket);
                //阻塞当前线程
                if (TimeoutObject.WaitOne(1000, false))//1s超时//StartHeck_flag为0时,破解按钮没被开启,能弹窗“网络正常”
                {
                    if (StartHeck_flag == 0)
                    {
                        MessageBox.Show("网络正常");
                    }
                    Time_Out = 0;
                }
                else
                {
                    if (StartHeck_flag == 0)
                    {
                        MessageBox.Show("连接超时");
                    }
                    Time_Out = 1;//超时标志
                }


                /*/6.0 像服务器发送消息
                 *
                 *  for (int i = 0; i < 10; i++)
                 *  {
                 *      Thread.Sleep(2000);
                 *      string sendMessage = string.Format("客户端发送的消息,当前时间{0}", DateTime.Now.ToString());
                 *      _socket.Send(Encoding.UTF8.GetBytes(sendMessage));
                 *      Console.WriteLine("像服务发送的消息:{0}", sendMessage);
                 *  }
                 */
            }
            catch (Exception ex)
            {
                _socket.Close();
                MessageBox.Show(ex.Message);//远程主机强迫关闭了一个连接/无法连接/连接失败/通讯失败
            }
        }
        void CheckTimeout()
        {
            CancelInvoke("SetTimeout");

            _tempHs.Clear();
            _bWaitCheck = false;

            DateTime      nowTime   = DateTime.Now;
            TimeoutObject minObject = null;
            float         minTime   = 0f;

            foreach (long timeoutId in _timeoutDic.Keys)
            {
                TimeoutObject timeoutObject = _timeoutDic[timeoutId];
                float         deltaTime     = (float)(nowTime - timeoutObject.dateTime).TotalMilliseconds / 1000f;
                if (deltaTime >= timeoutObject.timeout)
                {
                    _tempHs.Add(timeoutObject);
                }
                else
                {
                    deltaTime = timeoutObject.timeout - deltaTime;
                    if (minObject == null || deltaTime < minTime)
                    {
                        minObject = timeoutObject;
                        minTime   = deltaTime;
                    }
                }
            }

            foreach (TimeoutObject timeoutObject in _tempHs)
            {
                _timeoutDic.Remove(timeoutObject.ID);
                timeoutObject.DoTimeoutCallback();
            }

            if (minObject != null)
            {
                Invoke("SetTimeout", minTime);
            }
        }
Example #15
0
        /// <summary>
        /// Removes the action and stops the thread if necessary.
        /// </summary>
        /// <param name="timeoutObj">The timeout obj.</param>
        protected virtual void RemoveInternal(TimeoutObject timeoutObj)
        {
            lock (this.TimeoutObjects)
            {
                this.TimeoutObjects.Remove(timeoutObj);
                if (this.TimeoutObjects.Count == 0)
                    this.StopTimerThread();

                Monitor.PulseAll(this.TimeoutObjects);
            }
        }
Example #16
0
        private void RunTimerThread()
        {
            Thread        thread      = Thread.CurrentThread;
            TimeoutObject nextTimeout = null;

            while (true)
            {
                lock (this.TimeoutObjects)
                {
                    // The thread is no longer running so break out
                    if (this.TimerThread != thread)
                    {
                        break;
                    }

                    // If we have no items left then exit the thread
                    if (this.TimeoutObjects.Count == 0)
                    {
                        break;
                    }

                    // Get our next timeout object
                    nextTimeout = this.TimeoutObjects.Where(o => !o.IsExecuting).OrderBy(o => o.NextTick).FirstOrDefault();

                    // If we didn't find anything that means all timeouts are executing still
                    // So just wait indefinitely until someone wakes us up
                    if (nextTimeout == null)
                    {
                        Monitor.Wait(this.TimeoutObjects);
                        continue;
                    }

                    // If our next timeout is not ready then wait for it to be
                    var timeRemaining = nextTimeout.TimeRemaining;
                    if (timeRemaining.TotalMilliseconds > 0)
                    {
                        // Wait until we get pulsed or our timeout is up then make sure we're still running and try again
                        Monitor.Wait(this.TimeoutObjects, timeRemaining);
                        continue;
                    }

                    // If the object we're about to execute is a one time action then just remove it now
                    if (nextTimeout.Interval == TimeSpan.Zero)
                    {
                        nextTimeout.Dispose();
                    }
                }

                // Trigger the next timeout
                // Create a local variable to avoid issues with the closure
                var obj = nextTimeout;
                obj.IsExecuting = true;
                ThreadPool.QueueUserWorkItem(data =>
                {
                    // Execute the tick and then figure out the next tick time
                    try
                    {
                        obj.Tick();
                    }
                    catch (Exception exception)
                    {
                        Break();
                        Trace.WriteLine(exception, "TimeoutDispatcher");

                        try
                        {
                            if (obj.ExceptionHandler != null)
                            {
                                obj.ExceptionHandler(exception);
                            }
                        }
                        catch (Exception)
                        {
                            //if there was an exception in the exception handler we will just silence it.
                            Break();
                        }
                    }

                    obj.NextTick    = DateTime.Now.Add(obj.Interval);
                    obj.IsExecuting = false;

                    // If this is a repeating job then we should probably notify our thread
                    // That we updated the next tick time so it knows how long to wait
                    if (obj.Interval == TimeSpan.Zero)
                    {
                        return;
                    }

                    lock (this.TimeoutObjects)
                    {
                        // Since some time may have passed make sure we're still valid before signaling
                        if (this.TimeoutObjects.Contains(obj))
                        {
                            Monitor.PulseAll(this.TimeoutObjects);
                        }
                    }
                });
            }
        }
Example #17
0
        /// <summary>
        /// HttpPost方法
        /// </summary>
        /// <param name="Address">请求的地址(IP:端口)</param>
        /// <param name="method">方法名称</param>
        /// <param name="strPost">请求数据</param>
        /// <param name="dtStr">请求时间</param>
        /// <param name="Conifg">配置名</param>
        /// <param name="i">第几次请求</param>
        /// <param name="RecvTimeOut">返回超时</param>
        /// <param name="ReqTimeout">请求超时</param>
        /// <returns>返回数据</returns>
        public static string HttpPost(string Address, string method, string strPost, string dtStr, string Conifg = "", int i = 0, int RecvTimeOut = 3000, int ReqTimeout = 1000)
        {
            string innerErrorMessage = string.Empty;

            string data   = string.Empty;
            Socket socket = null;

            try
            {
                string[] strAddress = Address.Split(':');

                TimeoutObject.Reset();

                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                IPAddress ip = IPAddress.Parse(strAddress[0]);

                byte[] postBytes = Encoding.ASCII.GetBytes(UrlEncodeGB2312(strPost));

                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("POST /format=json&language=CSharp&method={0}{1} HTTP/1.1\r\n", method, string.IsNullOrEmpty(Conifg) ? string.Empty : string.Format("&USING={0}", Conifg));
                sb.Append("Content-Type: application/x-www-form-urlencoded\r\n");
                sb.AppendFormat("Host: {0}\r\n", Address);
                sb.AppendFormat("Content-Length: {0}\r\n", postBytes.Length);
                sb.Append("Connection: Keep-Alive\r\n\r\n");

                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, RecvTimeOut);

                socket.BeginConnect(new IPEndPoint(ip, Convert.ToInt32(strAddress[1])), CallBackMethod, socket);

                //阻塞当前线程
                if (!TimeoutObject.WaitOne(ReqTimeout, false))
                {
                    //连接超时
                    return(string.Empty);
                }

                byte[] sendData = Encoding.ASCII.GetBytes(UrlEncodeGB2312(sb.ToString()));

                byte[] nCon = new byte[sendData.Length + postBytes.Length];
                sendData.CopyTo(nCon, 0);
                postBytes.CopyTo(nCon, sendData.Length);

                socket.Send(nCon);

                byte[] recive = new byte[40960];

                int nlen   = 0;
                int ntotal = 0;
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"(?<=Content-Length:)\d{1,8}");

                while (true)
                {
                    int nrec = socket.Receive(recive);
                    if (nrec == 0)
                    {
                        break;
                    }
                    ntotal += nrec;
                    string header = Encoding.Default.GetString(recive);
                    if (nlen == 0)
                    {
                        System.Text.RegularExpressions.Match match = reg.Match(header);
                        if (match.Success)
                        {
                            nlen = Convert.ToInt32(match.Value);
                        }
                    }
                    data += header;
                    int npos = data.IndexOf("\r\n\r\n");
                    if (npos != -1)
                    {
                        data = data.Substring(npos + 4);
                    }
                    if (ntotal - 78 - nlen.ToString().Length >= nlen)
                    {
                        break;
                    }
                }

                socket.Shutdown(SocketShutdown.Both);
            }
            catch (Exception ex)
            {
                innerErrorMessage = string.Format("JetermClient.{0}的HttpPost{1}请求抛异常:{2}请求时间:{3}{2}请求EtermServer服务器地址:{4}{2}请求数据:{2}{5}{2}返回:{2}{6}{2}异常信息为:{2}{7}", method, (i > 0 ? string.Format("第{0}次", i) : string.Empty), Environment.NewLine, dtStr, Address, strPost, (string.IsNullOrWhiteSpace(data) ? "返回为空" : data), ex.ToString());
                log.Error(innerErrorMessage);
            }
            finally
            {
                if (socket != null)
                {
                    socket.Close();
                }
            }

            if (!string.IsNullOrWhiteSpace(innerErrorMessage))
            {
                throw new Exception(innerErrorMessage);
            }
            return(data);
        }
Example #18
0
        /// <summary>
        /// Adds the action and starts the thread if necessary.
        /// </summary>
        /// <param name="timeoutObj">The timeout obj.</param>
        protected virtual void AddInternal(TimeoutObject timeoutObj)
        {
            lock (this.TimeoutObjects)
            {
                this.TimeoutObjects.Add(timeoutObj);
                if (this.TimeoutObjects.Count == 1)
                    this.StartTimerThread();

                Monitor.PulseAll(this.TimeoutObjects);
            }
        }
Example #19
0
 /// <summary>
 /// Adds the specified timeout action.
 /// </summary>
 /// <param name="tick">The tick.</param>
 /// <param name="exceptionHandler">the exception handler </param>
 /// <param name="timeout">The timeout.</param>
 /// <returns></returns>
 public IDisposable Add(Action tick, Action<Exception> exceptionHandler, TimeSpan timeout)
 {
     var timeoutObj = new TimeoutObject(this, tick, exceptionHandler, timeout, TimeSpan.Zero);
     this.AddInternal(timeoutObj);
     return timeoutObj;
 }
Example #20
0
        /// <summary>
        /// Adds the specified repeating timeout action.
        /// </summary>
        /// <param name="tick">The tick.</param>
        /// <param name="exceptionHandler">The exception handler </param>
        /// <param name="interval">The interval.</param>
        /// <param name="initialDelay">The initial delay.</param>
        /// <returns></returns>
        public IDisposable AddRepeating(Action tick, Action<Exception> exceptionHandler, TimeSpan interval, TimeSpan initialDelay)
        {
            if (initialDelay <= TimeSpan.Zero)
                initialDelay = interval;

            var timeoutObj = new TimeoutObject(this, tick, exceptionHandler, initialDelay, interval);
            this.AddInternal(timeoutObj);
            return timeoutObj;
        }