关于TcpClient,Socket连接超时的几种处理方法

用TcpClient做通信的时候,经常发现网络连接不通的时候,代码就卡死在那里,TcpClient竟然没有超时的设定 泪奔啊 看来微软不是把所有工具准备得妥妥当当的啊

没办法 现在用线程来包装一下这个类 ,勉强可使用。

先上第一个类:这是网上的一种解决方案。

class TimeOutSocket
    {
        private static bool IsConnectionSuccessful = false;
        private static Exception socketexception;
        private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);
        public static TcpClient TryConnect(IPEndPoint remoteEndPoint, int timeoutMiliSecond)
        {
            TimeoutObject.Reset();
            socketexception = null;
            string serverip = Convert.ToString(remoteEndPoint.Address);
            int serverport = remoteEndPoint.Port;
            TcpClient tcpclient = new TcpClient();
            tcpclient.BeginConnect(serverip, serverport,
            new AsyncCallback(CallBackMethod), tcpclient);
            if (TimeoutObject.WaitOne(timeoutMiliSecond, false))
            {
                if (IsConnectionSuccessful)
                {
                    return tcpclient;
                }
                else
                {
                    throw socketexception;
                }
            }
            else
            {
                tcpclient.Close();
                throw new TimeoutException("TimeOut Exception");
            }
        }
        private static void CallBackMethod(IAsyncResult asyncresult)
        {
            try
            {
                IsConnectionSuccessful = false;
                TcpClient tcpclient = asyncresult.AsyncState as TcpClient;
                if (tcpclient.Client != null)
                {
                    tcpclient.EndConnect(asyncresult);
                    IsConnectionSuccessful = true;
                }
            }
            catch (Exception ex)
            {
                IsConnectionSuccessful = false;
                socketexception = ex;
            }
            finally
            {
                TimeoutObject.Set();
            }
        }
    }

插入第二种,自己实现的超时处理代码

 static void Main(string[] args)
        {
            CancellationTokenSource c = new CancellationTokenSource();
            CancellationToken token = c.Token;

            Task task = new Task(() =>
            {
                TcpClient client = new TcpClient(AddressFamily.InterNetwork);
                client.SendTimeout = 6000;
                client.ReceiveTimeout = 6000;
                client.Connect(IPAddress.Parse("192.168.0.49"), int.Parse("60000"));
                if (client.Connected)
                {
                    byte[] data = System.Text.Encoding.UTF8.GetBytes("AAAAABDEEKRJOWEQRIO@#$(*#@&%");
                    byte[] buffer = new byte[32];
                    string responseData = string.Empty;
                    using (NetworkStream stream = client.GetStream())
                    {
                        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                        StreamReader Reader = new StreamReader(stream, encode);
                        Console.WriteLine("\nResponse stream received");
                        Char[] read = new Char[16];
                        int count = 0;
                        do
                        {
                            count = Reader.Read(read, 0, 16);
                            String str = new String(read, 0, count);
                            Console.Write(str);
                        } while (count > 0);
                        Reader.Close();
                    }
                }
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        throw new OperationCanceledException();
                    }
                }
            }, token);

            task.Start();
            if (task.Wait(3000, token))
            {

            }
            else
            {
                c.Cancel();
                Console.WriteLine("任务已经取消");
            }

        }

OK,先写这么多吧

 

posted @ 2015-01-22 16:17  需要格局  阅读(6928)  评论(1编辑  收藏  举报