0

我正在尝试在字符串格式的列表视图中检索用户名。我想要做的是检索这些用户名并将它们存储在一个字符串数组中并通过网络发送它们,以便接收部分可以提取它们并将这些用户名放在列表视图中。

但问题是,我在通过网络发送字符串数组时遇到了麻烦。我知道如何通过网络发送字符串,但我不知道如何通过网络发送字符串数组。

我在想的是,也许我应该使用循环来存储和提取字符串?但我不知道该怎么做。

这是我的发送代码。

'Say, this array contains the following strings
Dim strData() As String = {"Dog", "Cat", "Mouse"}

If networkStream.CanWrite Then

       'This is not the proper way. What should I do here?
       Dim SentData As Byte()

       SentData = Encoding.ASCII.GetBytes(strData)

       NetworkStream.Write(SentData, 0, SentData.Length())

End If

这是我的接收代码。

Dim rcvData() As String

If networkStream.CanWrite Then

       'Again, I don't think this is the proper way of handling an array of strings.
       Dim ByteData(ClientSocket.ReceiveBufferSize) As Byte

       NetworkStream.Read(ByteData, 0, CInt(ClientSocket.ReceiveBufferSize))

       rcvData = Encoding.ASCII.GetString(ByteData)

End If
4

2 回答 2

1

ASCII.GetBytes 没有接受字符串数组的重载。在转换数据之前,您需要加入您的字符串数组,然后发送一个字符串。

Dim strData() As String = {"Dog", "Cat", "Mouse"}

If networkStream.CanWrite Then

   Dim toSend = String.Join(";", strData)
   Dim SentData As Byte()
   SentData = Encoding.ASCII.GetBytes(toSend)
   NetworkStream.Write(SentData, 0, SentData.Length())
End If

当然,在接收端你应该分离收到的字符串

 Dim rcvData As String

 If networkStream.CanRead Then
     Dim bytesReceived As Integer = 0
     Dim ByteData(ClientSocket.ReceiveBufferSize) As Byte
     Do
         bytesReceived = networkStream.Read(ByteData, 0, CInt(ClientSocket.ReceiveBufferSize))
         rcvData = rcvData + Encoding.ASCII.GetString(ByteData, 0, bytesReceived)
     Loop While networkStream.DataAvailable
     Dim strData = rcvData.Split(";")
 End If
于 2013-01-28T15:13:10.627 回答
0

您知道如何发送单个字符串,但不知道它们的数组吗?因此,将数组编码为字符串,然后发送. 尝试JSON(请参阅如何在 VB.NET 中对数组进行 JSON 编码?)或XML

于 2013-01-28T15:02:07.037 回答