用线程监听UDP广播

时间:2009-03-11 18:08:36

标签: .net vb.net udp listener

我正在向播放一条简单的消息。。*。255(我的ip的最后一部分改为255),我正在试着听它。代码没有返回错误,但我没有收到任何东西。在wireshark中,我可以看到broacast被正确发送,但每次都有不同的端口(我不知道这是不是很重要)。这是我代码的一些部分。

Private Sub connect()
    setip()
    btnsend.Enabled = True
    btndisconnect.Enabled = True
    btnconnect.Enabled = False
    receive()
    txtmsg.Enabled = True
End Sub

Sub receive()
    Try
        SocketNO = port
        rClient = New System.Net.Sockets.UdpClient(SocketNO)
        rClient.EnableBroadcast = True
        ThreadReceive = _
           New System.Threading.Thread(AddressOf receivemessages)
        If ThreadReceive.IsAlive = False Then
            ThreadReceive.Start()
        Else
            ThreadReceive.Resume()
        End If
    Catch ex As Exception
        MsgBox("Error")
    End Try
End Sub

Sub receivemessages()
    Dim receiveBytes As Byte() = rClient.Receive(rip)
    Dim BitDet As BitArray
    BitDet = New BitArray(receiveBytes)
    Dim strReturnData As String = _
                System.Text.Encoding.Unicode.GetString(receiveBytes)
    MsgBox(strReturnData.ToString)
End Sub

 Private Sub setip()
    hostname = System.Net.Dns.GetHostName
    myip = IPAddress.Parse(System.Net.Dns.GetHostEntry(hostname).AddressList(1).ToString)
    ipsplit = myip.ToString.Split(".".ToCharArray())
    ipsplit(3) = 255
    broadcastip = IPAddress.Parse(ipsplit(0) & "." & ipsplit(1) & "." + ipsplit(2) + "." + ipsplit(3))
    iep = New IPEndPoint(broadcastip, port)

End Sub

Sub sendmsg()
    Dim msg As Byte()
    MsgBox(myip.ToString)
    sclient = New UdpClient
    sclient.EnableBroadcast = True
    msg = Encoding.ASCII.GetBytes(txtmsg.Text)
    sclient.Send(msg, msg.Length, iep)
    sclient.Close()
    txtmsg.Clear()
End Sub

2 个答案:

答案 0 :(得分:3)

This article似乎正在完成您正在尝试做的事情,并且很好地解释了代码中的大量注释。

答案 1 :(得分:1)

要侦听UDP端口,必须绑定端口。这是我使用的一些c#代码。它使用一个接收线程来轮询套接字以获取消息。

Socket soUdp_msg = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,ProtocolType.Udp);
IPEndPoint localIpEndPoint_msg = new IPEndPoint(IPAddress.Any, UdpPort_msg);
soUdp_msg.Bind(localIpEndPoint_msg);

然后在我的接收线程中

 byte[] received_s = new byte[2048];
 IPEndPoint tmpIpEndPoint = new IPEndPoint(IPAddress.Any, UdpPort_msg);
 EndPoint remoteEP = (tmpIpEndPoint);

 while (soUdp_msg.Poll(0, SelectMode.SelectRead))
 {

    int sz = soUdp_msg.ReceiveFrom(received_s, ref remoteEP);
    tep = (IPEndPoint)remoteEP;

    // do some work
 }

 Thread.Sleep(50); // sleep so receive thread does not dominate computer