【问题标题】:how to set timeout for a socket c#如何为套接字c#设置超时
【发布时间】:2020-07-16 20:28:46
【问题描述】:

这里有一个可以正常工作的客户端连接。 我尝试了几种实现超时和失败的工具(如果客户端无法成功连接到服务器,则抛出异常并关闭套接字。 我的代码:

 public void connect(string IP, int port)
        {
            try
            {

                IPHostEntry host = Dns.GetHostEntry(ip);
                IPAddress ipAddress = host.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);


                sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);


                try
                {
                    // Connect to Remote EndPoint  
                    sender.Connect(remoteEP);

                    Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

【问题讨论】:

    标签: c# tcp connection timeout client


    【解决方案1】:

    可以使用 Socket.ConnectAsync 方法和计时器来解决这个问题,请参阅:

    https://stackoverflow.com/a/1062628/86611

    或者:

    https://stackoverflow.com/a/4708790/86611

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 2017-10-19
      • 2012-11-12
      相关资源
      最近更新 更多