使用线程监听 UDP 广播

发布于 2024-07-14 11:01:06 字数 1760 浏览 5 评论 0原文

我正在向 ..*.255 广播一条简单的消息(将我的 ip 的最后部分更改为 255),并且我正在尝试收听它。 该代码没有返回错误,但我没有收到任何内容。 在wireshark中,我可以看到广播已正确发送,但每次使用不同的端口(我不知道这是否有什么大不了的)。 这是我的代码的一些部分。

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

I'm broadcasting a simple message to ..*.255 (changing to 255 the last part of my ip) and i'm trying to listen to it. the code returns no error but i'm not receiving anything. In wireshark I can see the broacast is sent correctly, but with a different port each time (I don't know if that's a big deal). Here's some parts of my code.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

病毒体 2024-07-21 11:01:07

这篇文章似乎几乎完全符合您想要做的事情做并通过代码中的大量注释很好地解释了它。

This article seems to be doing almost exactly what you're trying to do and explains it pretty well with lots of comments in the code.

未蓝澄海的烟 2024-07-21 11:01:07

要监听 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

To listen to an UDP port you must bind the port. Here is some c# code that I use. It using a receive thread that polls the socket for the messages.

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);

Then in my receive thread

 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文