【发布时间】: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