【问题标题】:udpclient receive and broadcast problemudpclient接收和广播问题
【发布时间】:2011-08-23 21:17:53
【问题描述】:

我的这段代码一直给我带来两个问题。

第一

请求的地址在其上下文中无效

第二,它接收它发送的广播,我不想要这个。我只希望监听服务器应用接收广播

发送代码

Dim sendMessage As New structMessage
        sendMessage.Command = Command.IP
        Dim byteData As Byte() = sendMessage.ToByte()
        'Using UDP sockets

        epServer = New IPEndPoint(IPAddress.Any, iCurrUDPPort)

        'sckClientUDP.EnableBroadcast = True
        sckClientUDP.EnableBroadcast = True
        sckClientUDP.BeginSend(byteData, byteData.Length, _
                               CType(epServer, Net.IPEndPoint), _
                                New AsyncCallback(AddressOf sckClientUDP_DataArrival), _
                                Nothing)


        '## if server not found , increment port
        If iCurrUDPPort = iToPort Then
            iCurrUDPPort = iFromPort
        Else
            iCurrUDPPort = iCurrUDPPort + 1
        End If

接收代码

    Private Sub sckClientUDP_DataArrival(ByVal ar As IAsyncResult)
        Try
            Dim remoteEP As EndPoint = Nothing
            sckClientUDP.EndReceive(ar, CType(remoteEP, IPEndPoint))
            'Convert the bytes received into an object of type Data
            Dim recvMessage As New structMessage(byteData)
            'Accordingly process the message received
            Select Case recvMessage.Command
                Case Command.IP
                    ServerIP = recvMessage.IP
                    ServerPort = recvMessage.Port
                    ' try connect here (TCP)
            End Select

            byteData = New Byte(1023) {}

            'Start listening to receive more data from the user
            sckClientUDP.BeginReceive(New AsyncCallback(AddressOf sckClientUDP_DataArrival), Nothing)
        Catch generatedExceptionName As ObjectDisposedException
        Catch ex As Exception
            Debug.Print(ex.Message)
        End Try
end sub

我该如何解决这个问题?

【问题讨论】:

    标签: .net vb.net networking asyncsocket udpclient


    【解决方案1】:

    首先,您应该广播到实际的子网 IP 地址,而不是 IPAddress.Any。

    其次,您无法避免重复的数据包。广播套接字应该接收它广播的相同数据包。这是广播工作方式的一部分。您必须通过将发送者的 IP 地址与您的广播 IP 地址进行比较来过滤掉任何不需要的数据包,以查看它们是否匹配。

    【讨论】:

    • 谢谢,但是如何在代码中检测我的程序所在的子网?
    • 您可以使用IPAddress.Broadcast 而不是IPAddress.Any 向您连接的每个子网广播。如果您只想广播到特定的子网,那么您必须知道每个网络上分配的 IP 地址和子网掩码是什么,然后您可以通过使用子网掩码屏蔽 IP 地址来格式化合适的广播 IP。本文向您展示如何在 .NET 2.0+ 中查找 IP 和子网掩码:blogs.msdn.com/b/dgorti/archive/2005/10/04/477078.aspx
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 2010-12-28
    相关资源
    最近更新 更多