在TCP通信中服务端关闭了客户端可以重连吗能用C#写一个例子吗
在TCP通信中,如果服务端关闭了,客户端可以尝试重新连接。以下是一个用C#编写的示例代码:
using System;
using System.Net.Sockets;
using System.Threading;
class Client
{
static void Main(string[] args)
{
while (true)
{
try
{
TcpClient client = new TcpClient("localhost", 1234);
Console.WriteLine("Connected to server.");
// 在这里进行数据通信
}
catch (SocketException)
{
Console.WriteLine("Failed to connect to server. Retrying in 5 seconds...");
Thread.Sleep(5000);
}
}
}
}
在上面的代码中,我们使用了一个无限循环来尝试连接服务端。如果连接失败,则会等待5秒钟后再次尝试连接。您可以在循环中添加您的数据通信代码
原文地址: https://www.cveoy.top/t/topic/eGIO 著作权归作者所有。请勿转载和采集!