1

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

4

2 回答 2

2

您可以查看Xamarin。您可以使用 C# 创建 Android、iOS、Mac 和 Windows 应用程序,Xamarin Studio 会为您将其编译为本机应用程序。

于 2014-03-19T09:08:20.930 回答
0

使用语言转换器工具。你可以在这里找到一些不错的列表

它不会每次都给你一个 100% 的结果,但会让你接近最终结果,在这里和那里做一些小的改变,你会得到你想要的。

于 2014-03-19T09:04:43.057 回答