0

我对编写控制台应用程序很陌生。我不明白为什么当控制台运行并写入它收到的消息时,它会在控制台中创建一堆额外的行。我敢肯定这是愚蠢的,但我在不得已的情况下,因为谷歌上没有人显然对 vb.net 如此愚蠢。提前致谢!

Sub Main()
    Do
        Console.WriteLine("Waiting for connection...")
        server.Start()
        client = server.AcceptTcpClient()
        Console.WriteLine("Connected")
        Do
            stream = client.GetStream()
            Dim recvBytes(client.ReceiveBufferSize) As Byte
            stream.Read(recvBytes, 0, client.ReceiveBufferSize)
            Dim recvText As String = Encoding.ASCII.GetString(recvBytes)
            Console.WriteLine(recvText)
            responses = Console.ReadLine
            If responses = "close" Then
                stream.Close()
                client.Close()
                server.Stop()
                Environment.Exit(0)
            Else
                Dim sendBytes() As Byte = Encoding.ASCII.GetBytes(responses)
                stream.Write(sendBytes, 0, sendBytes.Length)
                Console.WriteLine("Message Sent")
            End If
            If client.Connected = False Then
                Console.WriteLine("Client is no longer connected")
                Exit Do
            End If
        Loop
    Loop
End Sub
4

2 回答 2

0

我相信以下行返回一个空字符串

Dim recvText As String = Encoding.ASCII.GetString(recvBytes)

因此,在打印出该行之前,只需验证它是否为空。修改后的代码如下:

Sub Main()
Do
    Console.WriteLine("Waiting for connection...")
    server.Start()
    client = server.AcceptTcpClient()
    Console.WriteLine("Connected")
    Do
        stream = client.GetStream()
        Dim recvBytes(client.ReceiveBufferSize) As Byte
        stream.Read(recvBytes, 0, client.ReceiveBufferSize)
        Dim recvText As String = Encoding.ASCII.GetString(recvBytes)
        If recvText <> "" Then Console.WriteLine(recvText)
        responses = Console.ReadLine
        If responses = "close" Then
            stream.Close()
            client.Close()
            server.Stop()
            Environment.Exit(0)
        Else
            Dim sendBytes() As Byte = Encoding.ASCII.GetBytes(responses)
            stream.Write(sendBytes, 0, sendBytes.Length)
            Console.WriteLine("Message Sent")
        End If
        If client.Connected = False Then
            Console.WriteLine("Client is no longer connected")
            Exit Do
        End If
    Loop
Loop

End Sub
于 2013-04-22T20:17:54.990 回答
0

我遇到的问题与接收缓冲区大小有关。一旦我实际设置了它,然后使用字符串生成器来构建最终的字符串;一切都很好。感谢所有的建议。这些建议导致了一些非常有趣和急需的关于我没有考虑过的事情的阅读,事实证明,需要更多地关注。

于 2013-04-27T16:52:40.167 回答