简体   繁体   English

Android客户端应用程序无法连接到Java PC服务器 - 无路由到主机错误

[英]Android Client app cannot connect to Java PC Server - No Route to Host Error

I'm building an app for Android that will communicate with a PC and exchange data. 我正在构建一个Android应用程序,它将与PC通信并交换数据。 I've been mainly going through several examples in learning how to make apps and how to use Java sockets. 我主要经历了几个学习如何制作应用程序以及如何使用Java套接字的例子。 One example that I have been trying to get to work is: 我一直努力工作的一个例子是:

http://lakjeewa.blogspot.com/2014/05/simple-android-client-server-application.html http://lakjeewa.blogspot.com/2014/05/simple-android-client-server-application.html

I've modified a few things from the code above (names of variables and key press functions) and when I use the IP Address: 10.0.2.2, and run the app in an emulator and the server on a desktop connected to a private network, the app and server works. 我已经从上面的代码中修改了一些内容(变量和按键功能的名称),当我使用IP地址时:10.0.2.2,并在模拟器中运行应用程序,并在连接到专用网络的桌面上运行服务器,应用程序和服务器工作。 I'm able to send a message from the app on the emulator to the server and the server receives it. 我能够从模拟器上的应用程序向服务器发送消息,服务器接收它。

However when I run the server on a laptop and the client app on an android phone that are both wirelessly connected to another private network, I get an error in the android studio console saying " No route to host ." 然而,当我在笔记本电脑上运行服务器和Android手机上的客户端应用程序无线连接到另一个专用网络时,我在android工作室控制台中收到一条错误消息“ 无路由到主机” I went into my laptops command terminal and was able to ping my phone. 我进了我的笔记本电脑命令终端,能够ping我的手机。 And I've replaced the area of the code with the correct IPv4 Address and socket. 我用正确的IPv4地址和套接字替换了代码区域。 I've also connected my laptop and phone to another wireless network and still cannot establish a connection. 我还将我的笔记本电脑和手机连接到另一个无线网络,仍然无法建立连接。

What could be the issue? 可能是什么问题? Is there something I must specify in the code to enable connections? 我必须在代码中指定一些启用连接的东西吗? Or do I have to do something with the network or hardware devices to establish the connection? 或者我是否必须使用网络或硬件设备来建立连接?

Please note: Code for activity, manifest and layout is basically the same as shown in the link, except for variable name changes and I removed the function: public boolean onCreateOptionsMenu(Menu menu) 请注意:活动,清单和布局的代码与链接中显示的基本相同,除了变量名称更改,我删除了函数: public boolean onCreateOptionsMenu(Menu menu)

Thank you for your help! 谢谢您的帮助!

EDIT 2 Below is my source code for the android client: 编辑2下面是我的Android客户端的源代码:

    import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    private Socket client;
    private PrintWriter printwriter;
    private EditText textField;
    private Button button;
    private String messsage;

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

        textField = (EditText) findViewById(R.id.editText1); // reference to the text field
        button = (Button) findViewById(R.id.button1); // reference to the send button

        // Button press event listener
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                messsage = textField.getText().toString(); // get the text message on the text field
                textField.setText(""); // Reset the text field to blank
                SendMessage sendMessageTask = new SendMessage();
                sendMessageTask.execute();
            }
        });
    }

    private class SendMessage extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            try {

                client = new Socket("192.168.1.37", 4444); // connect to the 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) {
                Context context = getApplicationContext();
                /* If I try to send a toast notification my app crashes
                String text = "Could not connect";
                int duration = Toast.LENGTH_SHORT;
                Toast notify = Toast.makeText(context, text, duration);
                notify.show();*/
                e.printStackTrace();
            } catch (IOException e) {
                Context context = getApplicationContext();
                /*String text = "Could not connect";
                int duration = Toast.LENGTH_SHORT;
                Toast notify = Toast.makeText(context, text, duration);
                notify.show();*/
                e.printStackTrace();
            }
            return null;
        }

    }
}

Source code for the server: 服务器的源代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author alexc
 */
public class JavaServer {

    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;

    public static void main(String[] args) throws IOException {
        try {
            serverSocket = new ServerSocket(4444); // Server socket

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

        System.out.println("Server started. Listening to the port 4444");
                int count = 0;
        while (count < 1000) {
                    count++;
            try {

                clientSocket = serverSocket.accept(); // accept the client connection
                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");
            }
        }
                serverSocket.close();
    }

}

Hey y'all so I got my friend's router which is a Linksys E1000 Wireless-N router from Cisco and tested my android app and Java server and it works. 嘿你们所以我得到了我朋友的路由器,这是思科的Linksys E1000 Wireless-N路由器,并测试了我的Android应用程序和Java服务器,它的工作原理。 Don't know what the exact configurations are but this what I did: 不知道确切的配置是什么,但这就是我做的:

  1. Enable DHCP on the router, otherwise you will have to set static IP Addresses on your PC and Android Phone 在路由器上启用DHCP,否则您必须在PC和Android手机上设置静态IP地址

  2. Make sure your PC and Android Phone are enabled to be discoverable on the network. 确保您的PC和Android手机在网络上可以被发现。 I just remembered on my PC when I connected to this router, it asked me do I want to be able to be discovered on the network 当我连接到这台路由器时,我只记得在我的电脑上,它问我是否希望能够在网络上被发现

  3. Turn off firewall (and antivirus), or keep the port open you want all your connections for your android app to go through. 关闭防火墙(和防病毒),或保持端口打开,你想要你的Android应用程序的所有连接通过。

If you still have issues, here are some general troubleshooting tips (as whatever devices you use will vary): 如果您仍有问题,请参阅以下常规故障排除提示(因为您使用的设备会有所不同):

  • If you are not getting assigned IP addresses for your PC or android Phone and DHCP is enabled, try resetting the router (turning it off and on again; or full system reset) 如果您没有为您的PC或Android手机分配IP地址并启用DHCP,请尝试重置路由器(将其关闭再打开;或完全重置系统)

  • For windows, open command prompt and type ipconfig and find your IPv4 address. 对于Windows,打开命令提示符并键入ipconfig并找到您的IPv4地址。 Make sure that you type the address in correctly. 确保正确键入地址。 Then in the commmand prompt type ping 'android phone's IP Address' For example: 然后在命令提示符下键入ping 'android phone's IP Address'例如:

    ping 192.168.1.121 ping 192.168.1.121

If you get a response that means your phone is on the network. 如果您收到回复表示您的手机在网络上。

Then try to ping the IPv4 address you found for ipconfig if your phone can ping it, then you are all good. 然后尝试ping你为ipconfig找到的IPv4地址,如果你的手机可以ping它,那么你们都很好。 If you can't ping it, try turning off the firewall and antivirus. 如果您无法ping通,请尝试关闭防火墙和防病毒软件。

Anyway thank you all for the help and suggestions. 无论如何,谢谢大家的帮助和建议。 Hope these suggestions help. 希望这些建议有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM