我的應用程序正在通過TCP接收命令,如果我試圖比較命令比較總是失敗。比較字符串總是失敗(字符串從字節()轉換)
消息被轉換爲字節()並返回,但應該在下面的示例中比較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
變量是含有相同的文字的情況下的字符串,但它未能通過比較:
請問您可以將其工作到最小的可重複範例嗎? – asawyer 2012-07-30 15:18:53
什麼是從套接字讀取的字節? ASCII編碼後產生的字符串是什麼?哪個字符與預期不同?正如@asawyer所說,請簡化這個例子到幾行代碼,它們重現了根本不涉及TCP通信的問題。例如,你的例子可以簡單地聲明一個字節數組,用預期的硬編碼值填充它,然後ascii將它編碼爲一個字符串,然後將它與預期的字符串進行比較。 – 2012-07-30 15:31:18
我懷疑問題根本不在於編碼,而是在您確定收到完整的消息之前立即提升「MessageReceived」事件。例如,當你調用'_tcpClient.GetStream()。Read'時,它可能只返回消息的第一部分,因爲這是迄今爲止所收到的全部內容。 – 2012-07-30 15:47:59