【问题标题】:Any String concat with previous one not showing VB.NET与前一个字符串连接的任何字符串均未显示 VB.NET
【发布时间】:2014-06-10 16:07:57
【问题描述】:

好的,我猜这是一个非常基本的问题,我不确定我的代码有什么问题。我与另一个字符串 (ClientName) 连接的任何字符串/字符都没有显示。事实上,它只是删除了 ClientName 之后的任何其他字符。

代码如下:

公共子聊天()

    While Link.Client.Connected

        Try

            NumberOfMessages = NumberOfMessages + 1 'Update number of clients.

            Stream = Link.GetStream 'Get the stream from Socket.

            Dim MessageIn, MessageOut As String

            MessageIn = GetDataFromStream(Stream)

            ClientName = GetClientName_Stream(MessageIn)

            MessageBox.Show(ClientName & "****") 'Here **** is removed :-/

            MainForm.UpdateMessage(ClientName & ">> " & MessageIn)


            MessageOut = MessageIn 'Echo Back same message

            SendDataFromStream(Stream, MessageOut)

        Catch e As Exception
        End Try
    End While
End Sub

这是从收到的消息中提取名称的函数:

私有函数 GetClientName_Stream(ByVal msg As String) As String

    Dim pos As Integer
    pos = msg.LastIndexOf("$")
    Dim name As String

    name = msg.Substring(pos + 1)
    Return name
End Function

客户端以这种格式发送消息:

Hello World$TheClientName

其中 TheClientName 是该客户端的名称。

这是 GetDataFromStream 函数:

私有函数 GetDataFromStream(Stream As NetworkStream) As String

    Dim Buffer(2000) As Byte 'The buffer in which the data will be stored in form of Bytes.
    Dim SizeOfData As Integer = Buffer.Length 'Link.ReceiveBufferSize 'The size of Buffer to read.
    Dim TheData As String 'The Data received from Stream.




    Stream.Read(Buffer, 0, SizeOfData) 'Read the Stream and store it in Buffer.

    TheData = System.Text.Encoding.ASCII.GetString(Buffer) 'Create String from Buffer.



    Return TheData
End Function

【问题讨论】:

  • 我误解了这个问题,所以我删除了我之前的答案,并将添加一个新答案。

标签: vb.net string-concatenation tcpserver


【解决方案1】:

问题是您将整个Byte 数组转换为String,而只有一部分数组是从Stream 填充的。这意味着您的 String 末尾有空字符。如果将文本附加到该String,则String 对象将包含这些字符,但是当您显示它时,只会显示第一个空字符之前的内容。问题在这里:

Stream.Read(Buffer, 0, SizeOfData)

TheData = System.Text.Encoding.ASCII.GetString(Buffer)

您需要做的是确定在第一行读取了多少个Bytes,然后在第二行仅将那么多Bytes 转换为String

Dim bytesRead = Stream.Read(Buffer, 0, SizeOfData)

TheData = System.Text.Encoding.ASCII.GetString(Buffer, 0, bytesRead)

这样,数组中未写入的部分中的所有零 Bytes 将不会被转换为空字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2013-10-11
    • 2011-12-06
    • 2011-06-04
    • 2013-03-04
    相关资源
    最近更新 更多