udpclient接收和广播问题

时间:2011-08-23 21:17:53

标签: .net vb.net networking asyncsocket udpclient

我有这个代码一直给我两个问题。

第一

  

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

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

发送代码

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

我如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

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

其次,你无法避免重复的数据包。广播套接字应该接收它广播的相同分组。这是广播如何运作的一部分。您必须通过将发件人的IP地址与广播IP地址进行比较来过滤掉任何不需要的数据包,以确定它们是否匹配。