当我的程序启动时,我有一个连接到端点的以下方法
ChannelSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var remoteIpAddress = IPAddress.Parse(ChannelIp);
ChannelEndPoint = new IPEndPoint(remoteIpAddress, ChannelPort);
ChannelSocket.Connect(ChannelEndPoint);
我还有一个计时器,它设置为每 60 秒触发一次 call CheckConnectivity
,它尝试将任意字节数组发送到端点以确保连接仍然有效,如果发送失败,它将尝试重新连接。
public bool CheckConnectivity(bool isReconnect)
{
if (ChannelSocket != null)
{
var blockingState = ChannelSocket.Blocking;
try
{
var tmp = new byte[] { 0 };
ChannelSocket.Blocking = false;
ChannelSocket.Send(tmp);
}
catch (SocketException e)
{
try
{
ReconnectChannel();
}
catch (Exception ex)
{
return false;
}
}
}
else
{
ConnectivityLog.Warn(string.Format("{0}:{1} is null!", ChannelIp, ChannelPort));
return false;
}
return true;
}
private void ReconnectChannel()
{
try
{
ChannelSocket.Shutdown(SocketShutdown.Both);
ChannelSocket.Disconnect(true);
ChannelSocket.Close();
}
catch (Exception ex)
{
ConnectivityLog.Error(ex);
}
ChannelSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var remoteIpAddress = IPAddress.Parse(ChannelIp);
ChannelEndPoint = new IPEndPoint(remoteIpAddress, ChannelPort);
ChannelSocket.Connect(ChannelEndPoint);
Thread.Sleep(1000);
if (ChannelSocket.Connected)
{
ConnectivityLog.Info(string.Format("{0}:{1} is reconnected!", ChannelIp, ChannelPort));
}
else
{
ConnectivityLog.Warn(string.Format("{0}:{1} failed to reconnect!", ChannelIp, ChannelPort));
}
}
因此,我如何测试上述内容是从我的以太网设备上物理拔下 LAN 电缆,允许我的代码尝试重新连接(显然失败)并重新连接 LAN 电缆。
但是,即使重新连接 LAN 电缆(能够 ping),我的 Reconnect 方法中的 ChannelSocket.Connect(ChannelEndPoint) 总是会抛出此错误
No connection could be made because the target machine actively refused it 192.168.168.160:4001
如果我要重新启动整个应用程序,它会成功连接。如何调整我的重新连接方法,这样我就不必重新启动我的应用程序来重新连接到我的以太网设备?