我正在学习如何通过以太网电缆链接的2台计算机之间的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)
一旦我告诉它继续,控制台窗口就会全黑。我假设它写了行然后继续滚动。我怎样才能使收到的消息保留在监听器的控制台输出上?
答案 0 :(得分:1)
我认为这是因为您将整个bytes
数组转换为“主机/侦听器”中的字符串。您只需要转换接收的实际字节,而不是整个缓冲区:
Dim actualBytes = myStream.Read(bytes, 0, bytes.Length)
receivedMessage = Encoding.ASCII.GetString(bytes, 0, actualBytes)