简体   繁体   中英

Socket not connected in my Android app

I've been working in a server/client application that needs to get the hour from a server working in my computer.

When I try to run this app in my phone it says that SOCKET NOT CONNECTED. I tried everything but it still not working.

The thread is working, but the socket is not connecting!

The permissions I used:

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

The MainActivity.java is:

package com.example.clientehora;

/* imports */


public class MainActivity extends Activity {

    Socket socket = new Socket();
    String SERVER_IP = "10.215.19.41";
    int SERVERPORT = 2000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new ClientThread()).start();

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    public void ejecutar(View view) {
        try {

            System.out.println("Hola amigo, si me presionaste! =D" + socket.getInetAddress() + socket.getPort());
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String cadena = br.readLine();
            System.out.println("LA CADENA ES: " +cadena);
            EditText et = (EditText)findViewById(R.id.fecha);
            et.setText(cadena);
            br.close();

        } catch (UnknownHostException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }



    class ClientThread implements Runnable {
        @Override
        public void run() {

            try {
                 System.out.println("Se ha conectado sin problemas");
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                socket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e1) {

                e1.printStackTrace();

            } catch (IOException e1) {

                e1.printStackTrace();

            }

        }

    }

}

This works for me to connect to my Win7 PC via USB (mTimeout is 5000):

mSocket = new Socket();
mSocket.setSoTimeout(mTimeout);
mSocket.connect(new InetSocketAddress(SERVER_IP, SERVERPORT), mTimeout);

I get the IP to use using this command on the PC:

InetAddress.getLocalHost().getHostAddress()

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