如何解决聊天连接随机异常
我通过计算机和车床建立了用于校正驱动装置的连接。 该连接是通过以下方式进行的eternet聊天:
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程序时,我已经看到它可以具有超时参数。在这种情况下,是否可以在超时较大的情况下做到这一点呢?
提前谢谢 帕特里克
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。