Reputation: 55
I am currently creating an Unity Android application (GearVR) that could receive UDP packets send with broadcast on the Wi-Fi. Unfortunately I can't receive any packet in my application. Here is the script which I attached to a 3d game object.
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();
}
}
With the program SocketTest 3.0, I send "TextTest" to the address 255.255.255.255, port 5000 (I also tried by targeting directly the IP of the smartphone, it didn't work either)
Thanks in advance
Upvotes: 4
Views: 4727
Reputation: 125315
Ran a quick test on your code and came to conclusion that your client code is fine. Replace all Console.WriteLine
with Debug.Log
and your will receive the data you are broadcasting. Console.WriteLine
doesn't display anything in Unity's console.
If the problem is still there, please understand that some OS will block you from broadcasting to 255.255.255.255
. If this is the case then get the IP of the device you are broadcasting from and replace the last octet
with 255
. Broadcast to that IP Address and that will also work just like 255.255.255.255
.
For example, if your IP is 192.168.1.13
, replace 13
with 255
. You should broadcast to 192.168.1.255
in this case.
Finally, put the code below in your client script to make sure you kill that Thread
when you click the Stop button in the Editor or you will have many problems during development.
void OnDisable()
{
if (udpListeningThread != null && udpListeningThread.IsAlive)
{
udpListeningThread.Abort();
}
receivingUdpClient.Close();
}
Upvotes: 3