我正在尝试编写一个非常简单的 UDP 客户端/服务器对,它将在同一台计算机上一起工作(目前),但我的数据包都没有被传递。下面的代码是一个 100% 完整的 VB.NET 控制台应用程序。它运行时不会抛出错误,但 mListener.Receive 命令永远不会返回。
问题1:为什么我没有收到任何数据包?
问题 2:为什么我不能让我的客户使用 IPAddress.Any 作为端点?当我尝试连接到 New IPEndPoint(IPAddress.Any, 10123) 时,我收到“请求的地址在其上下文 0.0.0.0:10123 中无效”异常。
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Module Module1
Sub Main()
Dim ep As New IPEndPoint(IPAddress.Loopback, 10123)
Dim s As New Server(ep)
Dim c As New Client(ep)
Do
Console.WriteLine("Waiting in main loop...")
Thread.Sleep(5000)
Loop
End Sub
End Module
Public Class Server
Private mBroadcaster As UdpClient
Public Sub New(ep As IPEndPoint)
mBroadcaster = New UdpClient
mBroadcaster.ExclusiveAddressUse = False
mBroadcaster.Connect(ep)
Dim sender As New Thread(AddressOf SendLoop)
sender.Start()
End Sub
Private Sub SendLoop()
Do
Dim msg As Byte() = Text.ASCIIEncoding.ASCII.GetBytes("Hello world")
Console.WriteLine("Sending...")
mBroadcaster.Send(msg, msg.Length)
Thread.Sleep(1000)
Loop
End Sub
End Class
Public Class Client
Private mListener As UdpClient
Public Sub New(ep As IPEndPoint)
mListener = New UdpClient
mListener.ExclusiveAddressUse = False
mListener.Connect(ep) 'Why can't I use IPAddress.Any here?
Dim poller As New Thread(AddressOf PollLoop)
poller.Start()
End Sub
Private Sub PollLoop()
Do
Dim ep As IPEndPoint = Nothing
Console.WriteLine(" Receiver listening...")
Dim incomingbytes As Byte() = mListener.Receive(ep)
Dim msg As String = Text.ASCIIEncoding.ASCII.GetString(incomingbytes)
Console.WriteLine(" Received: " & msg & " from " & ep.Address.ToString & ":" & ep.Port)
Loop
End Sub
End Class