比较字符串始终失败(从Byte()转换的字符串)

时间:2012-07-30 15:16:37

标签: vb.net

我的应用程序通过TCP接收命令,如果我尝试比较命令,则比较总是失败。

消息转换为byte()并返回但在下面的示例中应该比较ok?或者我错过了什么?

Imports MyApp.Client

Public Class Form1
    Public Delegate Sub MessageReceivedHandler(ByVal message As String)

    Private Sub Message_Received(ByVal message As String)
        'update the display using invoke
        Invoke(New MessageReceivedHandler(AddressOf PrintToScreen), New Object() {message})
    End Sub

    Private Sub PrintToScreen(ByVal msg As String)
        Select Case msg
            Case "#all"
                'Do Something
            Case Else
                'Do Something Else
        End Select
    End Sub
End Class


'Client class
Public Class Client
    Private _tcpClient As TcpClient
    Public Event MessageReceived As MessageReceivedHandler

    Public Sub Connect(ByVal address As IPAddress, ByVal port As Integer)
        _tcpClient = New TcpClient()
        Dim serverEndPoint As New IPEndPoint(address, port)
        _tcpClient.Connect(serverEndPoint)
        ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf Read))
    End Sub

    Public Sub Send(ByVal buffer As Byte())
        _tcpClient.GetStream().Write(buffer, 0, buffer.Length)
        _tcpClient.GetStream().Flush()
    End Sub

    Private Sub Read()
        Dim encoder As New ASCIIEncoding()
        Dim buffer As Byte() = New Byte(4095) {}
        Dim bytesRead As Integer
        While True
            Try
                bytesRead = _tcpClient.GetStream().Read(buffer, 0, 4096)
                RaiseEvent MessageReceived(encoder.GetString(buffer, 0, bytesRead).ToString)
            Catch ex As IO.IOException
                Application.Exit()
            End Try
        End While
    End Sub

    Public Sub Dispose()
        _tcpClient.Close()
    End Sub
End Class

该变量是一个包含与案例相同的文本的字符串,但未通过比较:

Msg Variable

1 个答案:

答案 0 :(得分:2)

发现问题,发送应用程序在转换为byte()并发送之前将vbNullChar添加到字符串的末尾。 (无法看到从接收端转换的字符串中删除它的方法)