首页 > 解决方案 > 如何为套接字c#设置超时

问题描述

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

 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#tcpconnectiontimeoutclient

解决方案


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

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

或者:

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


推荐阅读