所以我正在构建一个小程序来发送/接收 UDP 广播。我意识到不推荐使用 UDP,但我不知道 IP 地址。
这是客户端发送的内容:
'Send "Hello Message" to ALL UDPListners
Public Sub UDPSendHello()
Dim client As New UDPClient()
Dim ip As New IPEndPoint(IPAddress.Broadcast, 15000)
Dim bytes As Byte() = Encoding.ASCII.GetBytes("Hello?")
client.Send(bytes, bytes.Length, ip)
client.Close()
End Sub
对于服务器,我收到消息“hello”并找到 IP 地址,如下所示:
'Reciever (Server)
Private ReadOnly udp As New UdpClient(15000)
Public Sub UDPHelloListner()
udp.BeginReceive(AddressOf Receive, New Object())
End Sub
Private Sub Receive(ByVal ar As IAsyncResult)
Dim ip As New IPEndPoint(IPAddress.Any, 15000)
Dim bytes As Byte() = udp.EndReceive(ar, ip)
Dim message As String = Encoding.ASCII.GetString(bytes)
If message = "Hello?" Then
Dim sender As New IPEndPoint(IPAddress.Any, 15000)
Dim senderRemote As EndPoint = CType(sender, EndPoint)
My.Settings.clientIPAddress = (ip.AddressFamily.ToString() + ip.Address.ToString)
MessageBox.Show(My.Settings.clientIPAddress)
' ListBox1.Items.Add(My.Settings.clientIPAddress)
End If
UDPHelloListner()
End Sub
现在我可以使用 MessageBox.Show(My.Settings.clientIPAddress) 来显示发送消息的客户端的 IP 地址。所以上面的作品!
现在,如果我有 4 个该程序的实例以客户端的身份广播上述内容。 我如何列出运行客户端的这 4 个实例的每个 IP? 我使用了' ListBox1.Items.Add(My.Settings.clientIPAddress) 但它说“调用线程无法访问此对象,因为不同的线程拥有它。”