androidsocketsemulationdevice

Socket works on emulator not on device


I have an app that works on the emulator but not when tested on real device.
Whole program:

public class MainActivity extends Activity {
    Socket socket;
    String strg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connect();
    }
    private void connect()
    {
        socket = null;
        Thread t = new Thread(new Runnable(){
            @Override
            public void run(){
                try {
                    InetAddress serverAddr = InetAddress.getByName("xx.xx.xx.xx");
                    socket = new Socket(serverAddr, x);
                    strg = "ok";
                    runOnUiThread(new Runnable(){
                        @Override
                        public void run(){
                            ((TextView)findViewById(R.id.output)).setText(strg);
                        }
                    });
                    socket.close();
                } catch (IOException e) {
                    final IOException exp = e;
                    runOnUiThread(new Runnable(){
                        @Override
                        public void run(){
                            strg = "ex2 "+exp.getMessage();
                            ((TextView)findViewById(R.id.output)).setText(strg);
                        }
                    });                     
                }                   
            }
        });
        t.start();  
    }
}

So this i all code there is.
I connect to an external IP which only can accept the connection.
When i run on the emulator strg is "ok" and the server registers that a connection has been established.
When i run the code on the device i get error message. "java.net.ConnectException: failed to connect to /xx.xx.xx.xx (port x): connect failed: ETIMEDOUT (Connection timed out)"

I have <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> & <uses-permission android:name="android.permission.INTERNET" /> (Otherwise it won't work on the emulator.)

Any suggestions?


Solution

  • So I found the solution and it was wrong settings on the server firewall which was blocking my requests. Thanks greenapps :)