问题描述
我正在开发一个程序来与旧系统进行通信.我为此使用 System.IO.Ports.SerialPort.问题是当我发送更长的消息时,消息会损坏.我使用线路监听器并得到以下结果
I am developing a program to communicate with an old system. I use System.IO.Ports.SerialPort for this. The problem is when I send a longer message, the message bevome corrupt. I use a line listener and get the following results
我发送的内容
aa 01 00 00 12 03 06 18 02 c1 94 02 c1 94 00 00 00 00 00 00 00 00 00 00 00 00 1e fd
我得到了什么
c2 aa 01 00 00 12 03 06 18 02 c3 81 c2 94 02 c3 81 c2 94 00 00 00 00 00 00 00 00 00 00 00 00 1e c3 bd
我使用的代码是
_comPort.Encoding = new UTF8Encoding();
_comPort.PortName = PortName; //Com1
_comPort.BaudRate = BaudRate; //9600
_comPort.StopBits = StopBits; //1
_comPort.DataBits = DataBits; //8
_comPort.Parity = Parity; //None
_comPort.Open();
_comPort.Write(messageStr);
为什么数据会损坏,我该如何解决?
Why is data corrupted and how do I fix this?
推荐答案
我的猜测是 messageStr
是一个字符串,而您看到的是编码问题.您已经明确指定了 UTF-8 编码,所以这就是您得到的 - 但我怀疑这不是您真正想要的.
My guess is that messageStr
is a string, and you're seeing encoding issues. You've explicitly specified the UTF-8 encoding, so that's what you're getting - but I suspect it's not what you really want.
您已经显示了 二进制 数据,因此我假设您实际上想要发送该二进制数据 - 在这种情况下,您应该使用 Write(byte[], int, int)
过载.
You've shown binary data, so I assume you actually want to send exactly that binary data - in which case you should use the Write(byte[], int, int)
overload.
如果您真的想要编写文本数据,您可能只需要选择正确的编码 - 但您需要向我们提供更多信息,以便我们帮助您做出正确的选择.
If you really want to write text data, you probably just need to pick the right encoding - but you'll need to give us more information for us to help you make the right choice.
这篇关于数据在通过串行端口传输期间损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!