数据在通过串行端口传输期间被损坏
我正在开发一个程序来与旧系统进行通信。我为此使用 System.IO.Ports.SerialPort。问题是当我发送较长的消息时,消息就会损坏。我使用线路侦听器并得到以下结果
我发送的内容
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);
为什么数据损坏以及如何修复此问题?
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
What I sending
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
What I get
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
The code I'm using is
_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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测是
messageStr
是一个字符串,并且您遇到了编码问题。您已经明确指定了 UTF-8 编码,因此这就是您所得到的 - 但我怀疑这不是您真正想要的。您已经显示了二进制数据,所以我假设您实际上想要发送确切的二进制数据 - 在这种情况下,您应该使用
Write(byte[], int, int)
重载。如果您确实想要写入文本数据,您可能只需要选择正确的编码 - 但您需要向我们提供更多信息,以便我们帮助您做出正确的选择。
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.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.