在C#中,處理TCP/IP錯誤通常涉及到異常處理和錯誤恢復
try
{
// Your TCP/IP code here
}
catch (SocketException ex)
{
// Handle the SocketException
Console.WriteLine("SocketException: " + ex.Message);
}
catch (Exception ex)
{
// Handle other exceptions not related to sockets
Console.WriteLine("Exception: " + ex.Message);
}
NetworkInterface.GetIsNetworkAvailable()
方法來檢查網絡連接狀態。if (!NetworkInterface.GetIsNetworkAvailable())
{
Console.WriteLine("No network connection is available.");
return;
}
TcpClient.ReceiveTimeout
和TcpClient.SendTimeout
屬性。TcpClient client = new TcpClient();
client.ReceiveTimeout = 5000; // 5 seconds
client.SendTimeout = 5000; // 5 seconds
int retryCount = 0;
const int maxRetries = 3;
while (retryCount < maxRetries)
{
try
{
// Your TCP/IP code here
break;
}
catch (SocketException ex)
{
retryCount++;
Console.WriteLine($"SocketException: {ex.Message}. Retrying ({retryCount}/{maxRetries})...");
}
catch (Exception ex)
{
retryCount++;
Console.WriteLine($"Exception: {ex.Message}. Retrying ({retryCount}/{maxRetries})...");
}
}
if (retryCount == maxRetries)
{
Console.WriteLine("Max retries reached. Aborting.");
}
client.Close();
stream.Close();
通過遵循這些最佳實踐,你可以更有效地處理C#中的TCP/IP錯誤。