0

Hi I'm new to android and Im Trying to get my android app to connect to a my server that is running on my local computer. Im just trying to get the app to send a simple string message to the server first but keep getting an error. From the print out statements i can see that the app terminates as soon as it hits the line with the try in it so i believe there is an issue with creating the client connection. I have also enable Internet,ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE,READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE permissions

i tried changing the localhost to InetAddress.getLocalHost() but still wouldn't work

heres my code :

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import static java.net.InetAddress.getLocalHost;

public class MainActivity extends AppCompatActivity{
    private Button cam;
    private Socket client;
    DataOutputStream os;
    private String IP = "localhost";
    private static final String TAG = "testing";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (android.os.Build.VERSION.SDK_INT > 9)
        {
            StrictMode.ThreadPolicy policy = new                      
            StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        setContentView(R.layout.activity_main);



        cam = (Button) findViewById(R.id.Button_camera);
        cam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Log.v(TAG, "trying to connect to server");
                try {
                    client = new Socket("My IP address entered", 8080);
                    Log.v(TAG, "client socket initalised");
                    String hey = "hey";
                    os = new DataOutputStream(client.getOutputStream());
                    Log.v(TAG, "outptu stream created");
                    os.flush();
                    Log.v(TAG, "flush");
                    os.writeBytes(hey);
                    Log.v(TAG, "written to server");
                    os.close();


                } catch (UnknownHostException e) {
                    Log.v(TAG, "Unknown error");
                    Log.v(TAG, e.toString());
                } catch (IOException e) {
                    Log.v(TAG, "IO exception u numpty");
                    Log.v(TAG, e.toString());
                }
                Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                startActivity(intent);



            }
        });

    }
}

my code prints out the statement trying to connect to server but doesn't reach any of the other print out statements and my server is still not receiving anything

 connect failed: ETIMEDOUT (Connection timed out)
ACTION_DOWN before UnsetPressedState. invoking mUnsetPressedState.run()
I/Choreographer: Skipped 3792 frames!  The application may be doing too much work on its main thread.
Gujju123
  • 3
  • 4

2 Answers2

0

Localhost is the phone itself, not your computer. If on a simulator, localhost is the simulator, not your computer- the simulator doesn't know its a simulator, it has its own IP address. Fix the IP you're using.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • I've changed the localhost to my computer ip address where the server is running , still not reaching the server. Please see the edited question for the updated error . Thank you – Gujju123 Aug 16 '17 at 17:15
  • Make sure your WAN is set to allow traffic to that port, at least from inside the network. Make sure you aren't on cellular (use wifi). And get rid of that strict mode stuff- use a Thread like you're supposed to. Don't get into bad habbits early, doing networking on the main thread will lead to apps that either perform badly or get killed by the OS. – Gabe Sechan Aug 16 '17 at 17:17
  • Ive checked the port is open and can accept connections, when i remove the strict mode stuff the app crashes – Gujju123 Aug 16 '17 at 17:19
  • i get this error android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1155) – Gujju123 Aug 16 '17 at 17:20
  • Like I said- use a Thread. All networking should be done on a separate thread. Doing it on the main thread will cause the app to appear to freeze. – Gabe Sechan Aug 16 '17 at 17:31
  • sorry I'm new to programming, would i need to create a thread pool to do it on a thread ? can i just create a simple thread ? how would the code look like – Gujju123 Aug 16 '17 at 18:07
  • theres a way to disable network on main thread exception, dont remember how – Marcos Vasconcelos Aug 16 '17 at 18:09
  • @MarcosVasconcelos: use `StrictMode.setThreadPolicy()`, or set the project's `targetSdkVersion` to 9. See [Quick fix for NetworkOnMainThreadException](https://stackoverflow.com/questions/12650921/) – Remy Lebeau Aug 16 '17 at 19:53
  • @Gujju123: look at [`AsyncTask`.](https://developer.android.com/reference/android/os/AsyncTask.html) – Remy Lebeau Aug 16 '17 at 19:53
  • @MarcosVasconcelos There is- but it doesn't work on all devices, it creates bad apps, promoted bad habbits, and shouldn't be taught to anyone. – Gabe Sechan Aug 16 '17 at 19:54
  • @GabeSechan i know, but he seens to be not wanting to learn thread now, also, with the solution to enable the exception to not be thrown, your application will hang in the main thread making it inresponsible – Marcos Vasconcelos Aug 16 '17 at 20:27
  • If he doesn't want to learn the right way, we shouldn't help him to learn the wrong one- we should ignore him – Gabe Sechan Aug 16 '17 at 20:28
0

I believe this is definitely just an issue with your IP, you are obviously giving ti the wrong ip address because everything else is fine. I would recommend either accessing the terminal and using the ifconfig command to find your ip or access your network settings, if your using a mac like I am select network , advance options , select tcp/ip tab and use ipv4 address as the ip address. If that doesn't work try using a different port or checking your firewall setting on your local computer. Hope that helps.

atlantis.pd
  • 68
  • 1
  • 9