簡體   English   中英

使用廣播在Unity Android應用程序中接收UDP數據包

[英]Receiving UDP packets in Unity Android application with broadcast

我目前正在創建一個Unity Android應用程序(GearVR),它可以接收通過Wi-Fi廣播發送的UDP數據包。 不幸的是我無法在我的申請中收到任何數據包。 這是我附加到3d游戲對象的腳本。

public class UDPSceneScript : MonoBehaviour {
Thread udpListeningThread;
Thread udpSendingThread;
public int portNumberReceive;
UdpClient receivingUdpClient;

private void initListenerThread()
{
    portNumberReceive = 5000;

    Console.WriteLine("Started on : " + portNumberReceive.ToString());
    udpListeningThread = new Thread(new ThreadStart(UdpListener));

    // Run in background
    udpListeningThread.IsBackground = true;
    udpListeningThread.Start();
}

public void UdpListener()
{
    receivingUdpClient = new UdpClient(portNumberReceive);

    while (true)
    {
        //Listening 
        try
        {
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            //IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Broadcast, 5000);

            // Blocks until a message returns on this socket from a remote host.
            byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);

            if (receiveBytes != null)
            {
                string returnData = Encoding.ASCII.GetString(receiveBytes);
                Console.WriteLine("Message Received" + returnData.ToString());
                Console.WriteLine("Address IP Sender" + RemoteIpEndPoint.Address.ToString());
                Console.WriteLine("Port Number Sender" + RemoteIpEndPoint.Port.ToString());

                if (returnData.ToString() == "TextTest")
                {
                    //Do something if TextTest is received
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

void Start()
{
    initListenerThread();
}
}

使用程序SocketTest 3.0,我將“TextTest”發送到地址255.255.255.255,端口5000(我也嘗試直接定位智能手機的IP,它也沒有工作)

提前致謝

快速測試您的代碼並得出結論,您的客戶端代碼很好。 將所有Console.WriteLine替換為Debug.Log ,您將收到正在廣播的數據。 Console.WriteLine在Unity的控制台中不顯示任何內容。

如果問題仍然存在,請理解某些操作系統會阻止您廣播到255.255.255.255 如果是這種情況,則獲取您正在廣播的設備的IP,並將最后一個octet替換為255 廣播到該IP地址,這也將像255.255.255.255一樣工作。

例如,如果你的IP是192.168.1.13 ,更換13255 在這種情況下,您應該廣播到192.168.1.255

最后,將下面的代碼放在客戶端腳本中,以確保在單擊編輯器中的“停止”按鈕時終止該Thread ,否則在開發過程中會遇到很多問題。

 void OnDisable()
 {
     if (udpListeningThread != null && udpListeningThread.IsAlive)
     {
         udpListeningThread.Abort();
     }

     receivingUdpClient.Close();
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM