0

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

消息被转换为 byte() 并返回,但在下面的示例中应该比较好吗?还是我错过了什么?

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

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

消息变量

4

1 回答 1

2

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

于 2012-07-31T14:12:05.390 回答