C#判断以太网通讯断开
时间: 2024-09-27 21:01:32 浏览: 51
在C#中,判断以太网通讯是否断开通常涉及监听网络事件和异常处理。以下是一个基本示例,假设你正在使用`.NET Framework`下的`System.Net.Sockets`类库来进行网络通信:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
class EthernetMonitor
{
private TcpClient client;
public void StartMonitoring()
{
try
{
// 创建TCP客户端并连接到服务器
client = new TcpClient("ServerIpAddress", ServerPort);
// 开始接收数据流
NetworkStream networkStream = client.GetStream();
// 注册连接中断的事件处理器
client.Client.Disposed += Client_Disposed;
// 进入无限循环等待数据
byte[] buffer = new byte[1024];
while (true)
{
int bytesRead = networkStream.Read(buffer, 0, buffer.Length);
// 处理接收到的数据...
}
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.ConnectionReset ||
ex.SocketErrorCode == SocketError.ConnectionAborted)
{
Console.WriteLine("Ethernet connection has been lost.");
}
else
{
Console.WriteLine($"Network error occurred: {ex.Message}");
}
}
}
private void Client_Disposed(object sender, EventArgs e)
{
// 当TCP连接关闭或发生异常时,此方法会被调用
Console.WriteLine("Ethernet connection has been terminated.");
client.Close(); // 关闭连接
}
}
public static void Main(string[] args)
{
EthernetMonitor monitor = new EthernetMonitor();
monitor.StartMonitoring();
}
```
在这个例子中,我们创建了一个`TcpClient`实例,当连接丢失(如远程主机关闭连接)时,会触发`Disposed`事件。然后我们在`catch`块中捕获`SocketException`,检查特定的错误代码来判断是否是连接断开的情况。
阅读全文