zoukankan      html  css  js  c++  java
  • 关于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("
    Response 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,先写这么多吧

    人有三等:第三流的人,一辈子看不透人性本质与商场的游戏则,他们皆深陷在错觉与梦幻中 第二流的人,是看透了,明白了,但是却不能自拔,甚至是无可奈何 第一流的人,是不仅看透想通,并且开始学会怎样玩这场游戏,用怎样的技巧来应对你的人生
  • 相关阅读:
    Daemon Tools手工完全卸载方案
    不要轻易删除/windows/install下文件
    Dumpbin命令的使用
    v4l2 视频捕获
    2瓶4两酒,1个1.5两的酒杯
    n个平面分空间最多可分成多少份
    &#65279导致页面顶部空白一行解决方法
    Base64编码原理分析
    浏览器中“JavaScript解析器”工作原理
    IList转化为DataSet,解决了System.nullable()的问题
  • 原文地址:https://www.cnblogs.com/TianMaiCheng/p/4242027.html
Copyright © 2011-2022 走看看