Android / Java:套接字异常ENETUNREACH但ping工作正常

时间:2017-04-18 08:44:28

标签: java android sockets

我有一个新问题,我无法解决最后一个问题: Multicast : using joinGroup on a multicast socket (java/android) packet isn't received

所以我尝试了另一种方式。 我在我的计算机和客户端上启动服务器作为我的androiddevice上的应用程序。但是,当我试图连接到我的计算机时,我收到错误:

  

java.net.ConnectException:无法连接到/192.168.137.1(端口54321):连接失败:ENETUNREACH

但我确认我可以从我的计算机ping到设备,并在我的防火墙关闭时反转。我不明白为什么它可以通过ping操作使用套接字。

我的代码:

服务器

public class Server implements Runnable

{
private final ServerSocket serverSocket;

public Server() throws IOException {
    //serverSocket = new ServerSocket(Constant.SERVER_PORT);
    serverSocket = new ServerSocket(Constant.SERVER_PORT, 1000, InetAddress.getLocalHost());
}

public static void main(String[] args) throws IOException {
    new Server().open();
}

private void open()
{
    Socket client;
    BufferedReader in;
    PrintWriter out;

    while (true) {
        try {

            // TODO: 25/03/2017 Threaded Service
            client = serverSocket.accept();
            System.out.println("Client accepted");

            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            out = new PrintWriter(client.getOutputStream());
            Thread.sleep(200);
            out.println("CONNECTED");
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

@Override
public void run() {
    open();
    Scanner sc = new Scanner(System.in);
    sc.next();
    while(true);
}

我的活动中连接到服务器的线程:

    public class Home extends AppCompatActivity {

private HandlerConnectionRunnable handlerConnectionMsg;
private HandlerNetwork handlerNetwork;

private boolean connectionOver = false;

private InetAddress hotspotIP;

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

    handlerConnectionMsg = new HandlerConnectionRunnable();
    new Thread(new ConnectionRunnable()).start();
}

public void sendData(View view)
{
    if (!connectionOver)
        return;
}

@Override
protected void onDestroy() {
    super.onDestroy();
}

public void getFirstMessage()
{
    new Thread(new FirstMessage()).start();
}

private class ConnectionRunnable implements Runnable
{
    private static final String CONNECTION_MESSAGE_KEY = "connection_message";
    private static final String CURRENT_AP             = "current_ap";

    private static final int ACTIVATING_WIFI  = 0;
    private static final int CONNECTION_AP    = 1;
    private static final int CONNECTED        = 2;
    private static final int CONNECTION_ERROR = 3;

    private Message msg;

    @Override
    public void run()
    {
        msg = handlerConnectionMsg.obtainMessage();
        Bundle b = new Bundle();

        // Get the wifi manager
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        // Enable the wifi
        boolean wasEnabled = wifiManager.isWifiEnabled();

        msg = handlerConnectionMsg.obtainMessage();
        b = new Bundle();
        b.putInt("connection_message", ACTIVATING_WIFI);
        msg.setData(b);
        handlerConnectionMsg.sendMessage(msg);

        wifiManager.setWifiEnabled(true);
        // Wait for the connection
        while(!wifiManager.isWifiEnabled());

        boolean ret = true;

        // Connect to the access point and disable the connection to others
        if (wifiManager.isWifiEnabled() && wifiManager.startScan())
        {
            msg = handlerConnectionMsg.obtainMessage();
            b = new Bundle();
            b.putInt("connection_message", CONNECTION_AP);
            msg.setData(b);
            handlerConnectionMsg.sendMessage(msg);

            ret = connectToAP(wifiManager, "trainee_hotspot_test", "d0nt3nt3rThis");
            //ret = connectToAP(wifiManager, "trainee_test", "12345678");
        }

        if (!ret)
        {
            msg = handlerConnectionMsg.obtainMessage();
            b = new Bundle();
            b.putInt("connection_message", CONNECTION_ERROR);
            msg.setData(b);
            handlerConnectionMsg.sendMessage(msg);

            return;
        }

        /*
        WifiManager.MulticastLock multicastLock = wifiManager.createMulticastLock("mydebuginfo");
        //multicastLock.setReferenceCounted(true);
        multicastLock.acquire();
        */

        //WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        //int ipAddress = wifiInfo.getIpAddress();
        int ipAddress = wifiManager.getDhcpInfo().serverAddress;

        try {
            hotspotIP = InetAddress.getByName(convertToIp(ipAddress));
            //System.out.println(hotspotIP.getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }



        msg = handlerConnectionMsg.obtainMessage();
        b = new Bundle();
        // Valid connection
        b.putInt("connection_message", CONNECTED);
        b.putString("current_ap", wifiManager.getConnectionInfo().getSSID());
        msg.setData(b);
        handlerConnectionMsg.sendMessage(msg);

    }

    private String convertToIp(int ipAddress) throws UnknownHostException {
        byte[] address = { (byte)(0xff & ipAddress),
                (byte)(0xff & (ipAddress >> 8)),
                (byte)(0xff & (ipAddress >> 16)),
                (byte)(0xff & (ipAddress >> 24)) };

        return InetAddress.getByAddress(address).getHostAddress();
    }

    private boolean connectToAP(WifiManager wifi, String name, String pass)
    {
        // Create a new wifiConfiguration object
        WifiConfiguration wifiConfig = new WifiConfiguration();

        // Add informations to it
        wifiConfig.SSID = String.format("\"%s\"", name);
        wifiConfig.preSharedKey = String.format("\"%s\"", pass);

        // We add this configuration to the wifi manager and get the id
        int netId = wifi.addNetwork(wifiConfig);
        // Disconnect from the current AP
        wifi.disconnect();
        // Enable the hotspot with given SSID if it exists
        boolean status = wifi.enableNetwork(netId, true);
        wifi.reconnect();

        return status;
    }
}

private class HandlerConnectionRunnable extends Handler
{
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        Home.this.connectionOver = true;

        Bundle b = msg.getData();

        int connectionMsg = b.getInt(ConnectionRunnable.CONNECTION_MESSAGE_KEY);

        switch (connectionMsg)
        {
            case ConnectionRunnable.ACTIVATING_WIFI:
                Toast.makeText(Home.this, "The wifi will be activated", Toast.LENGTH_SHORT).show();
                break;
            case ConnectionRunnable.CONNECTION_AP:
                Toast.makeText(Home.this, "The connection to the current access point will be disabled", Toast.LENGTH_LONG).show();
                break;
            case ConnectionRunnable.CONNECTION_ERROR:
                Toast.makeText(Home.this, "The connection wasn't possible", Toast.LENGTH_SHORT).show();
                break;
            case ConnectionRunnable.CONNECTED:
                Toast.makeText(Home.this, "Connected to : " + b.getString(ConnectionRunnable.CURRENT_AP), Toast.LENGTH_SHORT).show();
                getFirstMessage();
                break;
        }
    }
}

private class HandlerNetwork extends Handler
{
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        Toast.makeText(Home.this, msg.getData().getString("NETWORK"), Toast.LENGTH_LONG).show();
    }
}

private class FirstMessage implements Runnable
{
    @Override
    public void run() {
        Socket socket = null;
        socket = new Socket();

        try {
            //socket = new Socket(hotspotIP, Constant.SERVER_PORT);
            socket = new Socket();

            socket.connect(new InetSocketAddress(hotspotIP, Constant.SERVER_PORT));

            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream());

            String read = in.readLine();

            Message msg = handlerNetwork.obtainMessage();
            Bundle b = new Bundle();
            b.putString("NETWORK", "CONNECTED");
            msg.setData(b);
            handlerNetwork.sendMessage(msg);

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

    }
}

}

感谢大家的回复

度过美好的一天

更新

我忘了说手机和电脑在同一个网络上,因为手机已连接到我的电脑热点。

更新2

我把整个课程都放在了客户端上,以免忘记代码的任何重要部分。

更新3 在使用Ray的链接后,我获得了:

显示名称:ip6tnl0 名称:ip6tnl0 显示名称:wlan0 姓名:wlan0 显示名称:tunl0 名称:tunl0 显示名称:sit0 姓名:sit0 显示名称:p2p0 名称:p2p0 InetAddress:/ fe80 :: 73:8df​​f:fefa:c4a3%p2p0%11 显示名称:ifb0 名称:ifb0 显示名称:ifb1 名称:ifb1 显示名称:lo InetAddress:/ :: 1%1%1 InetAddress:/127.0.0.1 显示名称:ccmni2 名称:ccmni2 0显示名称:ccmni0 名称:ccmni0 显示名称:ccmni1 名称:ccmni1

0 个答案:

没有答案