【发布时间】:2020-02-01 09:40:37
【问题描述】:
我有几个设备。程序必须不断 ping 这些设备。
遇到一个问题——如果连接丢失,那么我的程序除了连接丢失前的第一次轮询外什么都不显示,如果我恢复连接,那么 15 秒后程序将开始输出数据。
public async Task Start(string ip)
{
textBox1.AppendText("Begin");
textBox1.AppendText("\r\n");
Stopwatch watch = new Stopwatch();
int i = 0;
while (true)
{
watch.Restart();
using (TcpClient tcp = new TcpClient())
{
tcp.SendTimeout = 1000;
try
{
await tcp.ConnectAsync("192.168.127.23", 10001);
}
catch (SocketException)
{
Debug.Assert(!tcp.Connected);
}
watch.Stop();
if (tcp.Connected)
{
textBox1.AppendText(i.ToString() + ") " + watch.ElapsedMilliseconds.ToString() + " ms");
textBox1.AppendText("\r\n");
}
else
{
textBox1.AppendText(string.Format("{0}) Offline", i));
}
}
await Task.Delay(1000);
i++;
}
}
这是我添加的新代码。
public async Task Start(string ip)
{
while (true)
{
for (int i = 0; i < devicesListActivity.Count; i++)
{
devicesListActivity[i].DevicesList.DevicesTotalPing++;
string ipAdresDevice = devicesListActivity[i].DevicesList.DevicesName;
int portDevice = devicesListActivity[i].DevicesList.DevicesPort;
int activeDevice = devicesListActivity[i].DevicesList.DevicesActiv;
int imageDevice = devicesListActivity[i].DevicesList.DevicesImage;
int sendTimeDevice = devicesListActivity[i].DevicesList.DevicesTimeSend;
int respTimeDevice = devicesListActivity[i].DevicesList.DevicesTimeResp;
var cts = new CancellationTokenSource(sendTimeDevice);
var ct = cts.Token;
var t = await Task.Run<ServerStatus>(() =>
{
try
{
using (TcpClient client = new TcpClient())
{
client.ConnectAsync(ipAdresDevice, portDevice).Wait(sendTimeDevice);
ct.ThrowIfCancellationRequested();
client.Close();
return ServerStatus.Available;
}
}
catch (AggregateException ex) when (ex.InnerException.GetType() == typeof(SocketException))
{
if (((SocketException)ex.InnerException).SocketErrorCode == SocketError.ConnectionRefused)
return ServerStatus.Refused;
else
{
throw new Exception("Server did not respond");
}
}
catch (OperationCanceledException)
{
return ServerStatus.TimeOut;
}
}, ct);
switch (t)
{
case ServerStatus.Available:
devicesListActivity[i].DevicesList.DevicesSuccessPing++;
textBox1.AppendText($"{DateTime.Now.ToString()} Server available" + " " + ipAdresDevice + string.Format(" [{0}/{1}]", devicesListActivity[i].DevicesList.DevicesSuccessPing, devicesListActivity[i].DevicesList.DevicesTotalPing) + " " + System.Math.Round((double)(devicesListActivity[i].DevicesList.DevicesSuccessPing / devicesListActivity[i].DevicesList.DevicesTotalPing * 100)) +" %");
textBox1.AppendText("\r\n");
break;
case ServerStatus.Refused:
textBox1.AppendText($"{DateTime.Now.ToString()} Server refused connection." + " " + ipAdresDevice + string.Format(" [{0}/{1}]", devicesListActivity[i].DevicesList.DevicesSuccessPing, devicesListActivity[i].DevicesList.DevicesTotalPing) + " " + System.Math.Round((double)(devicesListActivity[i].DevicesList.DevicesSuccessPing / devicesListActivity[i].DevicesList.DevicesTotalPing * 100)) + " %");
textBox1.AppendText("\r\n");
break;
case ServerStatus.TimeOut:
textBox1.AppendText($"{DateTime.Now.ToString()} Server did not respond." + " " + ipAdresDevice + string.Format(" [{0}/{1}]", devicesListActivity[i].DevicesList.DevicesSuccessPing, devicesListActivity[i].DevicesList.DevicesTotalPing) + " " + System.Math.Round((double)(devicesListActivity[i].DevicesList.DevicesSuccessPing / devicesListActivity[i].DevicesList.DevicesTotalPing * 100)) + " %");
textBox1.AppendText("\r\n");
break;
}
// Wait 1 second before trying the test again
await Task.Delay(1000);
}
}
}
【问题讨论】:
-
您描述了当前的行为。你真正想看到/实现的行为是什么?
-
@MouseOnMars 我想看看当连接失败时,每次尝试都会离线显示。很抱歉我忘了添加这个。
标签: c# async-await tcpclient