大佬教程收集整理的这篇文章主要介绍了vb.net – 如何将串行端口通信读入缓冲区并解析出完整的消息,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
Private port As New serialPort("COM13",9600,Parity.None,8,StopBits.OnE) Private Sub port_DataReceived(ByVal sender As Object,ByVal e As serialDataReceivedEventArgs) Debug.Print(port.ReadExisTing()) End Sub Private Sub Form1_Load(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles MyBase.Load AddHandler port.DataReceived,New serialDataReceivedEventHandler(AddressOf port_DataReceived) port.open() End Sub
这工作得很好,但是偶尔它不会获得所有数据,并且返回结果是两个字符串而不是一个.
一个例子是如果com端口发送单词“HelLO2YOU”,它看起来像:
Hel LO2YOU
要么
HelLO2 YOU
如何在其中放置一个缓冲区,以确保在显示之前读取所有数据?
谢谢!
Public Class DataBuffer Private ReadOnly _startOfText As String = ASCII.GetChars(New Byte() {2}) Private ReadOnly _endOfText As String = ASCII.GetChars(New Byte() {4}) Public Event messageReceived(ByVal message As String) Public Event DataIgnored(ByVal text As String) Private _buffer As StringBuilder = new StringBuilder Public Sub AppendText(ByVal text As String) _buffer.Append(text) While processBuffer(_buffer) End While End Sub Private Function processBuffer(ByVal buffer As StringBuilder) As Boolean Dim foundSomethingToProcess As Boolean = false Dim current As String = buffer.ToString() Dim stxPosition As Integer = current.IndexOf(_startOfText) Dim etxPosition As Integer = current.IndexOf(_endOfText) If (stxPosition >= 0) And (etxPosition >= 0) And (etxPosition > stxPosition) Then Dim messageText As String = current.SubString(0,etxPosition + 1) buffer.Remove(0,messageText.Length) If stxPosition > 0 Then RaiseEvent DataIgnored(messageText.SubString(0,stxPosition)) messageText = messageText.SubString(stxPosition) End If RaiseEvent messageReceived(messageText) foundSomethingToProcess = True ElseIf (stxPosition = -1) And (current.Length <> 0) Then buffer.Remove(0,current.Length) RaiseEvent DataIgnored(current) foundSomethingToProcess = True End If Return foundSomethingToProcess End Function Public Sub Flush() If _buffer.Length <> 0 Then RaiseEvent DataIgnored(_buffer.ToString()) End If End Sub End Class
我还要提一下,在通信协议中,通常有一个校验和字节,通过它可以确定消息在发送方和接收方之间传输过程中是否被破坏.
以上是大佬教程为你收集整理的vb.net – 如何将串行端口通信读入缓冲区并解析出完整的消息全部内容,希望文章能够帮你解决vb.net – 如何将串行端口通信读入缓冲区并解析出完整的消息所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。