控制台在 VB.Net 中滚动太快

Console scrolling too fast in VB.Net

我正在学习如何在 Visual Basic 中通过以太网电缆连接的 2 台计算机之间的 TCP/IP 连接发送消息。当我发送消息时,控制台屏幕向下滚动太远,接收到的消息不再显示在主机的控制台上 window。当我创建一个输出消息数百次的 For 循环时,我可以看到消息在控制台 window 中快速滚动,但最后 window 仍为黑色,我认为这意味着window 继续滚动。

我目前正在向客户端控制台输入一条消息,并让监听器控制台输出这条消息。

这是我的 host/listener 代码:

Imports System.Net.Sockets
Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Imports Microsoft.VisualBasic


Module Module1

Sub Main()

    'Open listener at port 8
    Dim myHost As New TcpListener(8)
    myHost.Start()
    Console.WriteLine("Waiting for connection")


    Dim myClient As TcpClient = myHost.AcceptTcpClient
    Console.WriteLine("Connected")


    Dim myStream As NetworkStream = myClient.GetStream
    Dim bytes(myClient.ReceiveBufferSize) As Byte
    Dim receivedMessage As String


    myStream.Read(bytes, 0, CInt(myClient.ReceiveBufferSize))
    receivedMessage = Encoding.ASCII.GetString(bytes)

    Console.WriteLine("Message was: " & receivedMessage)
    System.Threading.Thread.Sleep(2000)
    Console.ReadLine()

    myClient.Close()
    myHost.Stop()

End Sub

End Module

这是我给客户端的代码,导入和上面一样:

Module Module1

  Sub Main()


    Dim myClient As New TcpClient  
    myClient.Connect("My IP", 8)     'Connects to laptop IP on port 8
    Dim myStream As NetworkStream = myClient.GetStream()

    Dim message As String
    message = Console.ReadLine
    Console.WriteLine("We are sending the read line")
    sendOverIP(message, myStream)

    Console.ReadLine()

End Sub


Public Sub sendOverIP(ByVal message As String, ByVal myStream As NetworkStream)
    Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(message) 'Turns message into ASCII bytes
    myStream.Write(sendBytes, 0, sendBytes.Length)


    Console.WriteLine("We sent: " & message)
End Sub

End Module 

我在侦听器中此时有一个断点

    Console.WriteLine("Message was: " & receivedMessage) 

一旦我告诉它继续,控制台 window 就会变成全黑。我假设它写下该行然后继续滚动。我怎样才能使接收到的消息保留在侦听器的控制台输出上?

我认为这是因为您正在将整个 bytes 数组转换为 "host/listener" 中的字符串。您只需要转换接收到的实际字节,而不是整个缓冲区:

Dim actualBytes = myStream.Read(bytes, 0, bytes.Length)
receivedMessage = Encoding.ASCII.GetString(bytes, 0, actualBytes)