我正在尝试检索字符串格式的列表视图中的用户名。我想要做的是检索这些用户名并将它们存储在一个字符串数组中并通过网络发送它们,以便接收部分可以提取它们并将这些用户名放在列表视图中。
但问题是,我在网络上发送一串字符串时遇到了不好的时间。我知道如何通过网络发送字符串,但我不知道如何通过网络发送字符串数组。
我在想的是,也许我应该使用循环来存储和提取字符串?但我不知道该怎么做。
这是我发送的代码。
'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
答案 0 :(得分: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
答案 1 :(得分:0)
您知道如何发送单个字符串,但不是它们的数组?因此,将数组编码为字符串,然后发送 。请尝试JSON(请参阅How can I JSON encode an array in VB.NET?)或XML。