Can blocking calls be used in a coroutine without it stopping the main thread?
I have a MonoBehaviour that is designed to send a UDP broadcast to obtain a server IP address on LAN that is listening for the broadcast. In my coroutine, I’m executing a UDPClient.Recieve
method to get back a message, and it seems to be halting my main thread entirely despite my correct use of yield
statements.
UdpClient client = new UdpClient();
Coroutine discoverAddress;
IEnumerator DiscoverAddress (
float timeout,
OnAddressDiscovered onAddressDiscovered,
OnTimeout onTimeout
) {
float timeWaited = 0;
yield return null;
for (;;) {
if (timeWaited >= timeout) break;
string address = AskForAddress();
if (address != null || address != "") {
onAddressDiscovered(address);
StopCoroutine(discoverAddress);
}
timeWaited += Time.deltaTime;
yield return null;
}
onTimeout();
client.Close();
}
string AskForAddress () {
IPEndPoint serverEp = new IPEndPoint(IPAddress.Any, 0);
client.EnableBroadcast = true;
byte[] requestData = Encoding.ASCII.GetBytes("SomeRequestData");
client.Send(
requestData,
requestData.Length,
new IPEndPoint(IPAddress.Broadcast, udpPort)
);
byte[] serverResponseData = client.Receive(ref serverEp);
string serverResponse = Encoding.ASCII.GetString(serverResponseData);
return serverEp.Address.ToString();
}