2

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.

  1. Trying to get class in android that behave as CancellationTokenSource in .NET
  2. There is some logic that works great in C# but I don't know how to implement it in android.

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

Viral Patel
  • 32,418
  • 18
  • 82
  • 110
ishigh
  • 31
  • 1
  • 1
  • 7
  • 1
    learning Java and rewriting is the best option. – Display Name Mar 19 '14 at 09:35
  • I agree, and I'm on it, but some of the classes are not similar at all and need lots of adjusts, some of them are easy such as TimeSpan and some are very hard... that is why I'm asking it :-) – ishigh Mar 19 '14 at 09:53

2 Answers2

3

You could check out Xamarin. You can create Android, iOS, Mac and Windows apps with C# and Xamarin Studio compiles it for you to native applications.

Tom Spee
  • 9,209
  • 5
  • 31
  • 49
  • It's free now! You can use it and do all your programming for Android and iOS in C#. And it is very mature now! – TChadwick Nov 18 '16 at 17:10
0

Use a language converter tool. You can find some nice ones listed HERE

It wont give you a 100% result every time, but will take you close to the final result where with a few minor changes here and there you'll get what you want.

Community
  • 1
  • 1
Viral Patel
  • 32,418
  • 18
  • 82
  • 110