简体   繁体   中英

Android App cannot connect to local server

I am developing an android application which is dependent on a node server. I want to be able to test both my android app and node server locally.

I have my node server running on my computer and try to access it from my android application (on my physical device) causes a 404 error code.

However the exact same code will work if I emulate android on my computer. Also the server works when I access it from my cell phone's browser.

I try to use the following code to detect the server in case the IP of my computer ever changes.

            byte[] ip = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(((WifiManager) activity.getSystemService(activity.WIFI_SERVICE)).getConnectionInfo().getIpAddress()).array();
            for(int i = 0; i < 256; i++) {
                ip[3] = (byte)i;
                try {
                    InetAddress addr = InetAddress.getByAddress(ip);
                    System.out.println("trying " + addr.getHostAddress());
                    if(addr.isReachable(5000)) {
                        System.out.println("yes");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

And it does not say yes for my computer's IP address.

Am I thinking of this wrong? Is there another way? Are there settings I am not thinking about?

I actually found that there is a command for forward requests from your mobile device to your computer which makes it so that you don't have to write the ip checking code. Simply use the following adb command

adb reverse tcp:8080 tcp:8080

where 8080 is your port number, the left is the port your phone is hitting and the right is the port running on your server so you can mix and match those numbers

Of course you can only run this command while your phone is hardwired and have to run it each time you disconnect your phone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM