首页 > 解决方案 > 聊天连接随机异常

问题描述

我通过计算机和车床建立了连接以进行驾驶校正。连接是通过以下方式完成的以太网聊天:

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 过程时,我看到它可以有一个超时参数。在这种情况下,用大超时做同样的事情可以吗?

提前谢谢帕特里克

标签: c#connectionchatethernet

解决方案


推荐阅读