Android Socket连接(权限被拒绝)

时间:2015-05-21 20:29:49

标签: java android sockets

我正在尝试从andriod连接到简单的java服务器。如果我从adb adb connect 127.0.0.1:4444连接,服务器正在运行并看到连接  或甚至与pc ip adb connect 192.168.1.104:4444 但是android得到java.net.SocketException: socket failed: EACCES (Permission denied)。 PC和Android是单个WIFI路由器。

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连接

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();

        }
    }
}

清单

<?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>

异常在mSocket = new Socket("127.0.0.1", 4444)

我做错了什么?

3 个答案:

答案 0 :(得分:0)

权限没问题,但问题由@JonasCz

表示
mSocket = new Socket("127.0.0.1", 4444)

您无法从设备访问127.0.0.1

答案 1 :(得分:0)

Tnx你们所有人。我通过重启WIFI路由器解决了这个问题。现在连接成功但我无法理解。如果有人可以向我解释这个问题,我将不胜感激。

答案 2 :(得分:0)

Android Client and Java Desktop Communication using Socket(为我工作) 最佳解决方案 您正在尝试在主线程上进行网络通信,这在Android 4.0+上是不允许的。要解决崩溃问题,只需将代码移到另一个线程(例如,您应该看一下AsyncTask)。

您可以执行以下操作:

私有类SendMessage实现了Runnable {     私人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();
    }
}

} 然后将onClick更改为此:

    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 

}