.net 通过网络发送字符串数组
我正在尝试检索字符串格式的listview中的用户名。我要做的是检索这些用户名,并将它们存储在字符串数组中,然后通过网络发送它们,以便接收部分可以提取它们并将这些用户名放在listview中 但问题是,我在通过网络发送字符串数组时遇到了麻烦。我知道如何通过网络发送字符串,但我不知道如何通过网络发送字符串和字符串数组 我想的是,也许我应该使用一个循环来存储和提取字符串?但我不知道该怎么做 这是我的发送代码。.net 通过网络发送字符串数组,.net,arrays,vb.net,string,tcpclient,.net,Arrays,Vb.net,String,Tcpclient,我正在尝试检索字符串格式的listview中的用户名。我要做的是检索这些用户名,并将它们存储在字符串数组中,然后通过网络发送它们,以便接收部分可以提取它们并将这些用户名放在listview中 但问题是,我在通过网络发送字符串数组时遇到了麻烦。我知道如何通过网络发送字符串,但我不知道如何通过网络发送字符串和字符串数组 我想的是,也许我应该使用一个循环来存储和提取字符串?但我不知道该怎么做 这是我的发送代码。 'Say, this array contains the following strin
'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
这是我的接收代码。
'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
您知道如何发送单个字符串,但不知道如何发送它们的数组?因此,将数组编码为字符串,并发送该字符串。请尝试(请参阅)或。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
ASCII.GetBytes没有接受字符串数组的重载。你的代码无法编译,这正是问题所在。重要的是,你不能简单地忽略
NetworkStream的结果。阅读,因为你不能保证一次就收到全部消息。是否将数组编码为字符串?这对我来说听起来很陌生,但我会试着看一下。你忽略了NetworkStream的结果。阅读并假设你正在一次阅读整个消息。哇!那纯粹是天才!谢谢你。我应该试试这个D@DanielKelley当然,你是对的,在现实世界的应用程序中,你需要做到故障安全,并检查收到的大小代码>字符(或任何用作分隔符的字符。使用分隔符肯定是最简单、最有效的方法,但如果数据大小不是主要问题,我建议使用XML或JSON。@Stevendogart我100%肯定不会。正如我所说,它将包含用户名。而这些用户名实际上是名字。所以,我真的不这么认为我想那些用户名会包含;
.LOL。无论如何,谢谢你指出这一点。我会记住的。:)