문제

간단한 메시지를 방송하고 있습니다 ..*. 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
도움이 되었습니까?

해결책

이 기사 당신이하려는 일을 거의 정확하게하고있는 것 같습니다. 코드의 많은 의견과 함께 잘 설명합니다.

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top