2015-07-09 73 views
0

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

我正在向客户端控制台输入消息,并让侦听器控制台输出此消息。

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

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) 

只要我告诉它继续,控制台窗口变成全黑。我假设它写行然后继续滚动。我怎样才能让接收到的消息停留在监听器的控制台输出上?

+0

尝试删除Thread.sleep代码行 - 这似乎是多余的我,你有一个的ReadLine紧随其后的是应该让你看到什么发生了。 – Chris

回答

1

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

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

此外,使用'bytes.Length'而不是'CInt(myClient.ReceiveBufferSize)'是一种更好的做法。 –

+0

@Idle_Mind好的建议,更新。 – Mark

+0

这是个问题,我的缓冲区太大了。谢谢。 – jalconvolvon