c# - 聊天连接随机异常
问题描述
我通过计算机和车床建立了连接以进行驾驶校正。连接是通过以下方式完成的以太网聊天:
public static void StartClient(string strIpAddress, string strPort)
{
// Connect to a remote device.
try
{
Serializers.Logger.WriteLog("StartClient " + strIpAddress + " port=" + strPort);
if (strIpAddress.Trim() == "-1")
strIpAddress = GetLocalIPAddress();
IPAddress ipAddress = IPAddress.Parse(strIpAddress);
int port = int.Parse(strPort);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketClient.BeginConnect(remoteEP, new AsyncCallback(ConnectClientCallback), socketClient);
OnNotification_Client?.Invoke(eSocketOperationType.INFO, "Client connected to " + strIpAddress + " port=" + strPort);
}
catch (Exception e)
{
MessageBox.Show("StartClient exc:" + e.ToString());
}
}
private static void ConnectClientCallback(IAsyncResult ar)
{
try
{
socketClient = (Socket)ar.AsyncState;
socketClient.EndConnect(ar);
}
catch (Exception e)
{
MessageBox.Show(e.Message); <-------here is fired the problem
}
}
整个系统是 24/7 运行的单元的一部分。一切正常,但有时(每天或多或少一次)我们会收到以下错误:
我的想法是在连接之前添加一系列 ping,以了解连接是否正常。运行在电池下方的 30 米长电缆会出现随机问题吗?
Ping pingSender = new Ping();
int iProblemCounter=0;
for (int i = 0; i < 10; i++)
{
PingReply reply = pingSender.Send(StrIpAddress);<----Should I here specify a shorter timeout?!?!
if (reply.Status != IPStatus.Success)
iProblemCounter++;
}
if (iProblemCounter!=0)
{
Task.Run(() =>
{
var dialogResult = MessageBox.Show("Detected " + iProblemCounter + " problems", "Network problem", MessageBoxButton.OK, MessageBoxImage.Warning);
});
}
另外有没有什么办法可以更改代码以使整个过程中的连接更加健壮?我有这个疑问,因为在实现 ping 过程时,我看到它可以有一个超时参数。在这种情况下,用大超时做同样的事情可以吗?
提前谢谢帕特里克
解决方案
推荐阅读
- php - 如果网站在 Google 搜索结果中列出,则防止包含 PHP 文件
- angular - 正则表达式匹配 Angular 代理中的各种 URL
- jmeter-plugins - 在 JMeter 中,为什么加载时间等于延迟?
- apache - Apache .htacess 重定向
- google-sheets - QUERY 和 IMPORTRANGE 的问题 | 谷歌表格
- swiftui - 在 Touch Bar 中显示 TabView 元素 - SwiftUI
- microsoft-graph-api - 图 api me/messages 端点不允许在选择列表中开始和结束日期时间
- javascript - Expo + FirebaseAuthentication(使用 Twitter)无法正常工作
- arrays - 主函数和自定义函数中数组的大小不同
- wpf - 如何从外部程序集访问资源?