c#自动重连服务器功能
class Program
{
public static Socket client=null;
static void Main(string[] args)
{
int i = 0;
while (true) //循环检测,
{
if (client == null)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4580);
try
{
client.Connect(iep);
Console.WriteLine("服务器连接成功!" + client.RemoteEndPoint + "\r\n");
//
Thread td1 = new Thread(() =>
{
int leng = 1024;
byte[] buffer = new byte[leng];
int r = 0;
while ((r = client.Receive(buffer)) > 0)
{
Console.WriteLine(Encoding.Default.GetString(buffer, 0, r));
}
Console.WriteLine(client.RemoteEndPoint + "退出连接!!");
client.Close();
client.Dispose();
client = null;
});
td1.IsBackground = true;
td1.Start();
}
catch
{
Console.WriteLine("服务器退出 ");
client.Close();
client.Dispose();
client = null;
}
}
Thread.Sleep(1000);
i++;
Console.WriteLine("客户端进行的连接次数为:"+i.ToString());
}
Console.ReadKey();
}
}