I'm using a very standard UDP client code. It works fine in Unity Editor. But when build to android phone, I got no response. The sender is a well tested windows program (I also tried other udp senders from online) and I'm only building a receiver client. The sender is in UDP broadcast mode and is sending to 255.255.255.255:60888. It works fine In Unity but when build on the phone, it prints nothing. However toggling the sender to direct ip of the phone, it works fine and prints out the data. I have tried putting the receive EndPoint with IPAddress.Broadcast/Any/255.255.255.255/192.168.1.255.
They all work in editor but none works in android. Tried other ports too and same. I have read something about multicast lock from android and tried, not working. Some suggested HTC is not receiving broadcast (hardware specific). However the phone (not HTC) has a built-in video player that can be triggered buy a udp broadcast. My sender can send through and pull up the player. I think that is a native app and using java Datagram Socket. I wonder if this is a Unity bug or firmware bug. Unity version tried: 5.6.3, 2017.2.1, 2017.4.2.
Code is below:
public class UDPClient : MonoBehaviour {
Thread receiveThread;
int remotePort = 60888;
int clientPort = 60666;
UdpClient _udpClient;
// Use this for initialization
void Start ()
{
if (Application.isEditor)
{
Application.runInBackground = true;
}
_udpClient = new UdpClient(clientPort);
_udpClient.Client.ReceiveBufferSize = 1024;
receiveThread = new Thread(new ThreadStart(ReceiveTask));
receiveThread.Start();
}
void ReceiveTask()
{
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Broadcast, 0);
while (true)
{
try
{
byte[] data = _udpClient.Receive(ref remoteEP);
if (data != null && data.Length > 0)
{
Debug.Log("received: " + remoteEP.ToString() + " length: " + data.Length + " data: " + data[1].ToString());
}
else {
Thread.Sleep(10);
}
}
catch (System.Exception ex)
{
throw (ex);
}
}
}
void CleanUp()
{
Debug.Log("cleanning Thread");
if (receiveThread != null)
{
receiveThread.Abort();
}
receiveThread = null;
_udpClient.Close();
_udpClient = null;
}
void OnApplicationQuit()
{
CleanUp();
}
}