C#未能将字符附加到字符串上,但仅在一种方法中

问题描述 投票:0回答:1

我正在PLC和Unity3d模拟器之间编写TCP解决方案。我遇到了最困惑的问题,只是添加一个';'到我发送到PLC的字符串的末尾。

这是我的代码:

public void extractSpeed(string PLCSpeed) { //coneverts the socket message to belt speed and assigns it to belt
    if (!isRollers) {
        Int32.TryParse(beltScript.convID, out int j);

        if (j < 10) {
            convID = "0"+beltScript.convID;
        }
        if (j >= 10) {
            convID = beltScript.convID;
        }
    }
    if (isRollers) {
        Int32.TryParse(rollerScript.convID, out int j);

        if (j < 10) {
            convID = "0"+rollerScript.convID;
        }
        if (j >= 10) {
            convID = rollerScript.convID;
        }
    }
    if (PLCSpeed.StartsWith("B"+convID)) { 
        string finalPLCSpeed = PLCSpeed.Substring(4, 4);
        finalSpeed=float.Parse(finalPLCSpeed);
        //finalSpeed=finalSpeed;
        start = true;
        Debug.Log("Extracted Speed to Belt "+convID+": "+finalSpeed);
        testString = PLCSpeed;
        testString += ";";
        Debug.Log("TestString: "+testString);
        socket.sendData(testString);
        return;
    }else { //catch invalid message
        //Debug.Log("Failed to extract speed!");
        return; 
    }
}

如您所见,

testString = PLCSpeed;
        testString += ";";
        Debug.Log("TestString: "+testString);
        socket.sendData(testString);
        return;

是我尝试在其中添加';'的地方到字符串。当我记录值时,我得到的原始字符串不带';'。当我将值发送到PLC时,我得到的原始字符串是一条消息,而第二条消息仅带有';'。其他方法可以正常工作并发送正常。就是这种方法,即使当我在套接字脚本中的sendData方法处添加消息时,所有消息都获得“;”通过此方法发送的数据除外。我也可以在一条消息中发送更长的字符串,所以我不认为这是由于缓冲区长度或其他原因造成的。最奇怪的部分是我记录了我通过sendData发送的每条消息,但是并没有记录发送';'的日志,而是在PLC上以单独的消息的形式接收到它。

注意,PLCSpeed标记内的数据始终为B + ID + Speed。例如:B010300。

我添加了';'将字符串发送到Unity时,将其发送到PLC上的字符串,然后设置速度后,将其发送回PLC进行验证。当我放置';'在PLC中工作正常,但是我仍然无法在PLCSpeed的末尾附加任何字符串。好像它被标记为常量,但不是。

c# string sockets tcp plc
1个回答
0
投票

感谢@AlexeiLevenkov,我想通了。

PLC正在发送\ 0 x256。这是由于我的缓冲区为256bytes。我看不到它们,因为C#将它们当作空格或其他东西来处理。使用String.Replace,我能够直观地检测到它们。

日志:

“数据:B010150; XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX]

所以我们有它。 PLC是做任何事情的噩梦,而套接字是噩梦中最极端的事情。

感谢您的帮助!

© www.soinside.com 2019 - 2024. All rights reserved.