【问题标题】:List each IP from UDP Broadcast列出来自 UDP 广播的每个 IP
【发布时间】:2013-10-17 19:12:05
【问题描述】:

所以我正在构建一个小程序来发送/接收 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) 但它说“调用线程无法访问此对象因为不同的线程拥有它。”

【问题讨论】:

    标签: c# wpf vb.net sockets udpclient


    【解决方案1】:

    如果你使用 WPF,试试这个:

    Dispatcher.Invoke(Sub() ListBox1.Items.Add(My.Settings.clientIPAddress))
    

    如果您使用 WinForms:

    Invoke(Sub() ListBox1.Items.Add(My.Settings.clientIPAddress))
    

    在这两种情况下,我的意思是您的代码在 Window 类中。

    【讨论】:

    • 谢谢。我得看看 Dispatch.Invoke 做了什么。
    • 简而言之,在非 GUI 线程中调用的 Receive() 方法。因此,此方法中对 UI 元素的任何修改都不是线程安全的。 Dispatcher.Invoke 在 GUI 线程中调用委托,因此该委托中的任何修改都成为线程安全的。
    猜你喜欢
    • 2013-10-26
    • 2010-09-28
    • 2011-07-18
    • 1970-01-01
    • 2011-05-28
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多