I'm new to android. I've implemented kind of a hole punching in C# and I'm trying to implement the same logic in android.
Some of the classes from .NET solution that I Implemented new classes in android such as TimeSpan, though there are some classes that I need to implement and I got stacked.
CODE:
private static Boolean rec_and_wait(TimeSpan interval)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
byte[] data = new byte[1024];
IAsyncResult ar = socket.BeginReceive(data, 0, data.Length, SocketFlags.None, null, null);
int res = WaitHandle.WaitAny(new WaitHandle[] { ar.AsyncWaitHandle, _cancellationTokenSource.Token.WaitHandle }, interval.Add(TimeSpan.FromSeconds(10))); // allow extra 10 seconds for network delay
switch (res)
{
case 0: // response
return true;
case WaitHandle.WaitTimeout: // time out
case 1: //cancelled
default: // should not happen
return false;
}
}
catch
{
return false;
}
finally
{
if (socket != null)
{
socket.Close();
socket.Dispose();
socket = null;
}
}
}
Thanks