UDP from AndroidEmulator (--Genymotion--) to local

2019-02-19 19:26发布

I simply try to send and receive data between MonodroidApp(AndroidEmulator) and a localDevServer. I understand localhost is specially mapped to "10.0.2.2" on AndroidEmulator, so I did the following, but the app does not respond.

    System.Text.Encoding enc = System.Text.Encoding.UTF8;
        string sendMsg = "testtest";
        byte[] sendBytes = enc.GetBytes(sendMsg);

        int localPort = 39000;
        var udp = new System.Net.Sockets.UdpClient(localPort);

        //send data
        string remoteHost = "10.0.2.2";//"127.0.0.1";
        int remotePort = 15000;
        udp.Send(sendBytes, sendBytes.Length,
            remoteHost, remotePort);

        //receive data
        System.Net.IPEndPoint remoteEP = null;
        byte[] rcvBytes = udp.Receive(ref remoteEP);
        string rcvMsg = enc.GetString(rcvBytes);
        Console.WriteLine("received data:{0}", rcvMsg);
        Console.WriteLine("sender address:{0}/port:{1}",
            remoteEP.Address, remoteEP.Port);

This code is verified to work with Mono for Mac and the localDevServer with the pointer: remoteHost = "127.0.0.1"

so,

remoteHost = "10.0.2.2" pattern does not work.

What do I miss? Anyone, any thought?

Thank you.

1条回答
贼婆χ
2楼-- · 2019-02-19 19:58

Ok, one important thing I forgot to mention is The emulator I use for android is Genymotion.

So, it appears to be that "10.0.2.2" does not point localhost as default.

http://blog.zeezonline.com/2013/11/access-localhost-from-genymotion/

In my environment(OSX 10.9) with Genymotion,the localhost address from the emulator is

"10.0.3.2", and the code works.

查看更多
登录 后发表回答