我是编写控制台应用程序的新手。我无法弄清楚为什么在运行时会在控制台中创建一堆额外的行并写入收到的消息。我确定这是愚蠢的,但我是最后的手段,因为google上没有人显然对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
答案 0 :(得分: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
答案 1 :(得分:0)
我遇到的问题与接收缓冲区大小有关。一旦我实际设置它,然后使用字符串构建器来构建最终字符串;一切都很好。感谢所有的建议。这些建议引发了一些非常有趣且非常需要的关于我未考虑的事情的阅读,并且事实证明,需要更加关注。