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,先写这么多吧

    人有三等:第三流的人,一辈子看不透人性本质与商场的游戏则,他们皆深陷在错觉与梦幻中 第二流的人,是看透了,明白了,但是却不能自拔,甚至是无可奈何 第一流的人,是不仅看透想通,并且开始学会怎样玩这场游戏,用怎样的技巧来应对你的人生
  • 相关阅读:
    【洛谷3214】[HNOI2011] 卡农(思维)
    【洛谷2609】[ZJOI2012] 数列(高精度)
    【洛谷4501】[ZJOI2018] 胖(二分+RMQ)
    【洛谷4726】【模板】多项式指数函数(多项式 exp)
    uC/OS-II之入门与介绍20160525
    [转]Delphi 关键字详解
    [转]单元文件结构
    Delphi ComboBox的属性和事件、及几个鼠标事件的触发
    Delphi 用ToolButton和MonthCalendar实现DateTimePicker的功能
    Delphi 动态改变Rzsplitter的Orientation(方向)属性
  • 原文地址:https://www.cnblogs.com/TianMaiCheng/p/4242027.html
Copyright © 2011-2022 走看看