Android套接字ConnectException ENETUNREACH

时间:2016-03-24 07:32:27

标签: java android sockets

我正尝试通过普通的wifi连接使用Socket连接在2个Android设备(Moto G和Nexus 5)之间建立连接。

我有一个以服务器/客户端模式运行的应用程序。该应用程序在两台设备上运行。

当我将我的MotoG设置为服务器时,我能够完美地从我的客户端应用程序(Nexus)发送数据。但是,这不适用于相反的情况。我最终得到以下错误 -

  

java.net.ConnectException:无法连接到SERVERIP(端口8080):连接失败:ENETUNREACH(网络无法访问)

服务器代码 -

public class ServerThread implements Runnable {

    public void run() {
        try {
            if (SERVERIP != null) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus
                                .setText("Listening on IP: " + SERVERIP);
                    }
                });
                serverSocket = new ServerSocket(8080);
                while (true) {
                    // LISTEN FOR INCOMING CLIENTS
                    Socket client = serverSocket.accept();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            serverStatus2.setText("Connected.");
                        }
                    });

                    try {
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                        client.getInputStream()));
                        String line = null;
                        while ((line = in.readLine()) != null) {
                            final String currLine = line;
                            Log.i("Server Activity",currLine);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    String origString = serverStatus2.getText().toString();
                                    String newString = origString + "\n" + currLine;
                                    serverStatus2.setText(newString);
                                    ToneGenerator tone = new ToneGenerator(AudioManager.STREAM_NOTIFICATION,90);
                                    tone.startTone(ToneGenerator.TONE_PROP_ACK,10);
                                }
                            });
                        }
                        break;
                    } catch (Exception e) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                serverStatus
                                        .setText("Oops. Connection interrupted. Please reconnect your phones.");
                            }
                        });
                        e.printStackTrace();
                    }
                }
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus
                                .setText("Couldn't detect internet connection.");
                    }
                });
            }
        } catch (final Exception e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    serverStatus.setText("Error" + e.getMessage());
                }
            });
            e.printStackTrace();
        }
    }
}

// GETS THE IP ADDRESS OF YOUR PHONE'S NETWORK
private String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface
                .getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf
                    .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e("ServerActivity", ex.toString());
    }
    return null;
}

@Override
protected void onStop() {
    super.onStop();
    try {
        // MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
        serverSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

客户 -

    public class ClientThread implements Runnable {

    public void run() {
        try {
            if (socket==null){
                initSocketConn();
            }
            //connected = true;
            //while (connected) {
                try {
                    Log.d("ClientActivity", "C: Sending command.");
                    if (out==null){
                        out = new PrintWriter(
                                new BufferedWriter(new OutputStreamWriter(
                                        socket.getOutputStream())), true);
                    }
                    // WHERE YOU ISSUE THE COMMANDS
                    out.println(edtMessage.getText().toString());
                    Log.d("ClientActivity", "C: Sent.");
                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }
            //}
            //socket.close();
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;
        }
    }
}

private void initSocketConn(){
    try{
        InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
        Log.d("ClientActivity", "C: Connecting...");
        socket = new Socket(serverAddr,
                8080);  //THIS IS WHERE THE ERROR IS THROWN
    }
    catch (Exception ex){
        ex.printStackTrace();
    }
}

我在网上查了一下&amp;尝试了不同的选项,比如使用不同的端口号,但它没有用。我很困惑为什么当Moto是服务器时代码完美运行但是当NExus是服务器时给出错误???请帮忙!

Logcat -

03-29 07:25:06.065 20592-20611/com.shriwas.samplesocketapp D/OpenGLRenderer: endAllActiveAnimators on 0xb7ca02d8 (RippleDrawable) with handle 0xb7d24240
03-29 07:25:08.957 20592-21470/com.shriwas.samplesocketapp D/ClientActivity: C: Connecting...
03-29 07:25:08.958 20592-21470/com.shriwas.samplesocketapp W/System.err: java.net.ConnectException: failed to connect to /fe80::8c3a:e3ff:fe5d:2e0d%p2p0%25 (port 8080): connect failed: ENETUNREACH (Network is unreachable)
03-29 07:25:08.963 20592-21470/com.shriwas.samplesocketapp W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:124)
03-29 07:25:08.963 20592-21470/com.shriwas.samplesocketapp W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
03-29 07:25:08.963 20592-21470/com.shriwas.samplesocketapp W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)
03-29 07:25:08.963 20592-21470/com.shriwas.samplesocketapp W/System.err:     at java.net.Socket.startupSocket(Socket.java:590)
03-29 07:25:08.963 20592-21470/com.shriwas.samplesocketapp W/System.err:     at java.net.Socket.<init>(Socket.java:226)
03-29 07:25:08.964 20592-21470/com.shriwas.samplesocketapp W/System.err:     at com.shriwas.samplesocketapp.MyClientActivity.initSocketConn(MyClientActivity.java:108)
03-29 07:25:08.964 20592-21470/com.shriwas.samplesocketapp W/System.err:     at com.shriwas.samplesocketapp.MyClientActivity.access$300(MyClientActivity.java:20)
03-29 07:25:08.964 20592-21470/com.shriwas.samplesocketapp W/System.err:     at com.shriwas.samplesocketapp.MyClientActivity$ClientThread.run(MyClientActivity.java:77)
03-29 07:25:08.964 20592-21470/com.shriwas.samplesocketapp W/System.err:     at java.lang.Thread.run(Thread.java:818)
03-29 07:25:08.964 20592-21470/com.shriwas.samplesocketapp W/System.err: Caused by: android.system.ErrnoException: connect failed: ENETUNREACH (Network is unreachable)
03-29 07:25:08.964 20592-21470/com.shriwas.samplesocketapp W/System.err:     at libcore.io.Posix.connect(Native Method)
03-29 07:25:08.964 20592-21470/com.shriwas.samplesocketapp W/System.err:     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
03-29 07:25:08.964 20592-21470/com.shriwas.samplesocketapp W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
03-29 07:25:08.964 20592-21470/com.shriwas.samplesocketapp W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
03-29 07:25:08.965 20592-21470/com.shriwas.samplesocketapp W/System.err:    ... 8 more
03-29 07:25:08.966 20592-21470/com.shriwas.samplesocketapp D/ClientActivity: C: Sending command.
03-29 07:25:08.971 20592-21470/com.shriwas.samplesocketapp E/ClientActivity: S: 

错误

  

java.lang.NullPointerException:尝试调用虚方法   &#39; java.io.OutputStream java.net.Socket.getOutputStream()&#39;在null   对象参考
  在   com.shriwas.samplesocketapp.MyClientActivity $ ClientThread.run(MyClientActivity.java:84)   在java.lang.Thread.run(Thread.java:818)       03-29 07:25:08.971 20592-21470 / com.shriwas.samplesocketapp D / ClientActivity:C:已关闭。

0 个答案:

没有答案