1

I'm trying to connect from andriod to simple java server. Server is running and see connection if i do connect from adb adb connect 127.0.0.1:4444 or even with pc ip adb connect 192.168.1.104:4444 but android get java.net.SocketException: socket failed: EACCES (Permission denied). PC and android is in single WIFI router.

MyServer

public class Server {

    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;
    private static String serverIp = "10.0.2.15";

    public static void main(String[] args) {
        try {

            serverIp = getServerIp();

            if(serverIp != null){

                System.out.println("Listenning on IP:" + serverIp);

            }

            serverSocket = new ServerSocket(4444); // Server socket

        } catch (IOException e) {
            System.out.println("Could not listen on port: 4444  " + e.toString());
        }

        System.out.println("Server started. Listening to the port 4444");

        while (true) {
            try {


                clientSocket = serverSocket.accept(); // accept the client connection


                if(clientSocket.getInputStream().read() != -1){

                    System.out.println("Socket connection");

                } else {

                    System.out.println("Client disconected");

                }

                inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader); // get the client message
                message = bufferedReader.readLine();

                System.out.println(message);
                inputStreamReader.close();
                clientSocket.close();

            } catch (IOException ex) {
                System.out.println("Problem in message reading  " + ex.toString());
            }
        }

    }

    public static String getServerIp(){

        try{

            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
                    en.hasMoreElements();){
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAdress = intf.getInetAddresses();
                        enumIpAdress.hasMoreElements();){

                        InetAddress inetAddress = enumIpAdress.nextElement();
                        if(!inetAddress.isLoopbackAddress()){

                            return inetAddress.getHostAddress().toString();

                        }

                    }

            }

        } catch (SocketException e){

            System.out.println(e.toString());

        }

        return null;
    }
}

MyClient connection

public class ServerConnection extends AsyncTask<SocketAddress, String, String> {

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

        try {

            mSocket = new Socket("127.0.0.1", 4444);//test ip
                            //192.168.1.104:4444 - real ip of the server returns the same

            PrintWriter printwriter = new PrintWriter(mSocket.getOutputStream(), true);
            printwriter.write("this is test"); // write the message to output stream

            printwriter.flush();
            printwriter.close();
            mSocket.close();

            Log.i(LOG_TAG, "Socket connecting to " + params[0].toString());

            return null;
        } catch (IOException e) {

            e.printStackTrace();
            Log.i(LOG_TAG, "===================ERROR====================" +
                    "\n" +
                    e.toString());

            return e.toString();

        }
    }
}

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.stas.clientserverconnection" >

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Exception is on mSocket = new Socket("127.0.0.1", 4444) line

What am i doing wrong?

Mattia Maestrini
  • 32,270
  • 15
  • 87
  • 94
Stanislav Bondar
  • 6,056
  • 2
  • 34
  • 46

2 Answers2

0

The permissions are ok but the problem is indicated by @JonasCz

mSocket = new Socket("127.0.0.1", 4444)

You don´t have access to 127.0.0.1 from your device!

Jorgesys
  • 124,308
  • 23
  • 334
  • 268
0

Android Client and Java Desktop Communication using Socket (worked for me) BEST SOLUTION You are trying to make network communication on the main thread, which is not permitted on Android 4.0+. To solve the crash just move your code to another Thread (You should have a look at AsyncTask for example).

You can do something like that:

private class SendMessage implements Runnable { private String mMsg;

public SendMessage(String msg) {
    mMsg = msg;
}

public void run() {
    try {

        client = new Socket("localhost", 7575);  //connect to server
        printwriter = new PrintWriter(client.getOutputStream(),true);
        printwriter.write(messsage);  //write the message to output stream

        printwriter.flush();
        printwriter.close();
        client.close();   //closing the connection

    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

} And then change the onClick to this:

    public void onClick(View v)  
       { 
       messsage = textField.getText().toString();

       textField.setText("");      //Reset the text field to blank new

       Thread(new SendMessage(message)).start();    // start a new thread to make the communication in the background 

}