2017-04-10 77 views
0

如何從此代碼中獲取字符串而不是char數組?VB.NET TCP服務器套接字編程 - 從字節接收字符串

客戶端代碼:

  stm = tcpClient.GetStream() 
      Dim ascenc As New ASCIIEncoding 
      Dim byteData() As Byte = ascenc.GetBytes(strMessage(counter)) 
      Thread.Sleep(2000) 
      Console.WriteLine("Transmitted ") 
      stm.Write(byteData, 0, byteData.Length()) 

Server代碼:

Dim size As Integer = TcpSocket.Receive(bitData) 
      Dim chars(size) As Char 
      For i As Integer = 0 To size 
       chars(i) = Convert.ToChar(bitData(i)) // i want to get the string directly, how ? 
      Next 
      Dim newString As New String(chars) 
      Console.WriteLine(newString) 
      strMessage(counter) = newString 
+0

[嘗試](https://msdn.microsoft.com/en-us/library/ms172827.aspx)[使用Google](https://www.dotnetperls.com/convert-string-byte- array-vbnet)[at](http://stackoverflow.com/questions/1003275/how-to-convert-byte-to-string)[all?](http://www.convertdatatypes.com/Convert-Byte -Array-to-String-in-VB.net.html) –

回答

1

你已經擁有了它你的代碼,我建議實施:

Dim MyString As String = New String(MyArray) 

如果你想字節數組轉換你可以使用:

Dim MyString As String = Encoding.ASCII.GetString(bytes) 
+0

他已經這樣做了,但是:'Dim newString As New String(chars)'。他想要轉換字節數組,而不是迭代它來創建一個char數組。 –

+0

@VisualVincent是的,這就是爲什麼我編輯我不明白他的問題。然後一個簡單的:Encoding.ASCII.GetString(字節) – Mederic

+0

這就是他想要的,是的。我在回答中寫道(除了我用他的方法而不是靜態屬性)。 –

1

您也可以在服務器上使用ASCIIEncoding。只需使用它的GetString() method而不是GetBytes()

Dim ascenc As New ASCIIEncoding 
Dim newString As String = ascenc.GetString(bitData)