【问题标题】:Console scrolling too fast in VB.NetVB.Net 中的控制台滚动太快
【发布时间】:2015-07-10 05:25:44
【问题描述】:

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

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

这是我的主机/监听器代码:

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) 

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

【问题讨论】:

  • 尝试删除 Thread.Sleep 行 - 这对我来说似乎是多余的,因为紧随其后的 ReadLine 应该可以让您看到发生了什么。

标签: vb.net tcp tcpclient tcplistener


【解决方案1】:

我认为这是因为您将整个 bytes 数组转换为“主机/侦听器”中的字符串。您只需要转换接收到的实际字节,而不是整个缓冲区:

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

【讨论】:

  • 此外,最好使用bytes.Length 而不是CInt(myClient.ReceiveBufferSize)
  • 这是问题所在,我的缓冲区太大。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-27
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多