Problem when creating socket in android to server on pc

0

I am doing a chat for a project in the grade I am in, I already have a client and server that work in java on the PC.

Now I wanted to make a client in mobile version. The point is that I am stuck in the creation of the socket , since it throws me for a generic exception and I can not make it work. I'll stick the client code to see if you can help me out:

public class chat extends AppCompatActivity {
    private Socket socket;
    private TextView tvChat;
    private EditText etMensaje;
    private String mensaje;
    private int puerto;
    private InetAddress ip;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        tvChat =(TextView)findViewById(R.id.tvChat);
        tvChat.setText("");
        etMensaje = (EditText)findViewById(R.id.etMensaje);
            tvChat.setMovementMethod(new ScrollingMovementMethod());
        String temp;
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null){
            temp = (String)extras.get("IP");
            try {
                ip=InetAddress.getByName(temp);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            tvChat.append(ip.toString());
            p=Integer.parseInt((String)extras.get("Puerto"));
            tvChat.append(String.valueOf(p));
        }
        Runtime runtime = Runtime.getRuntime();
        try{
            Process mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 192.168.1.137");
            int mExitValue = mIpAddrProcess.waitFor();
            if (mExitValue == 0){
                tvChat.append("Ha salido bien");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            socket = new Socket(ip,p);
        } catch (UnknownHostException uhe){
            Toast.makeText(this, "La ip no apunta a ningun servidor disponible. " + uhe.getMessage(), Toast.LENGTH_LONG).show();
        } catch (IOException ioe){
            Toast.makeText(this, "Error de entrada y salida. "+ ioe.getMessage(),Toast.LENGTH_LONG).show();
        } catch (Exception e){
            Toast.makeText(this, "Error genérico. "+ e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

The funny thing is that by executing it on the mobile, the ping does it to me, but it does not connect ...

    
asked by walkerdeath 09.11.2017 в 20:41
source

1 answer

1

You can not establish the connection from the main thread , to prevent the UI from freezing, you have to launch the connection from a secondary thread.

An asynchronous task (Asyncasck) is defined by a calculation that runs on a secondary thread and whose result we want to be published in the user interface thread.

Add permission on your Manifest.

<uses-permission android:name="android.permission.INTERNET" />

Create a class by extending the AsyncTask class:

private class Conectar extends AsyncTask<String, Void, Boolean> {


        @Override
        protected Boolean doInBackground(String... params) {

           SERVER_IP = params[0];
           SERVER_PORT = params[1];
           TIME_OUT = params[2];


            try {
                socket = new Socket();
                socket.connect(new InetSocketAddress(SERVER_IP, Integer.valueOf(SERVER_PORT)), Integer.valueOf(TIME_OUT));
                Log.v(TAG,"Socket conectado");

                return true;
            } catch (IOException ex) {
                Log.v(TAG,"Socket NO conectado");
                return false;
            }

        }


    }

Establish a procedure to call that class.

private Conectar mCon = null;

private boolean setConectar(String IP, String Puerto, String TimeOut){

        mCon = new Conectar();
        mCon.execute(IP,Puerto,TimeOut);//En milisegundos

        try {

            if(mCon.get(TIME_OUT, TimeUnit.MILLISECONDS)) {
                return true;
            }else{
                return false;
            }

        } catch (TimeoutException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return false;
        }

    }

In the part of your code call setCoenctar ().

if(setConectar("xxx.xxx.xxx.xxx","3333","5000")){
   //Si esta conectado haga algo
}
    
answered by 09.11.2017 в 23:27