Java服务器android客户端通过不同网络进行通信

标签 java android sockets client-server

我正在实现聊天应用程序,其中服务器基于java,客户端在android中。我的服务器代码是使用套接字编程用java语言编写的。当我将我的Android手机(互联网已打开)与笔记本电脑连接并启动服务器和客户端时,它工作正常。在我的客户端应用程序中,我必须输入服务器计算机的 IP 地址,如下所示 192.168..。当客户端向服务器发送消息时,服务器将响应返回给客户端。没关系。

但是当我从不在我家庭网络中的其他Android手机运行客户端时(假设我的 friend 在他家里并尝试通过互联网连接java服务器(在我家里))。然后服务器没有显示连接建立。 我还尝试在启动时将我的公共(public) IP 地址从 google 放入客户端应用程序,但仍然没有响应。

服务器代码..

public class SimpleChatServer {
 static int port_num =4444;
    public static void main(String[] args) {

        ServerSocket serverSocket = null;
        Socket clientSocket = null;

        try {
            serverSocket = new ServerSocket(port_num);
            System.out.println("Server started. Listening to the port 4444. Waitng for the client.");
            clientSocket = serverSocket.accept();
            System.out.println("Client connected on port 4444.");
            port_num++;
        } catch (IOException e) {
            System.out.println("Could not listen on port: 4444");
            e.printStackTrace();
            return;
        }

请问哪位 friend 可以告诉我我该怎么办?如何将客户端连接到服务器? ipconfig 中的 IP 地址是什么?Google 中我的 IP 公共(public)地址是什么?

这是我的 Android 客户端代码。

     public class SimpleClientServerChatActivity extends Activity {

            private EditText textField,ipaddrs;
            private Button button, start;
            private TextView textView;
            private Socket client;
            private PrintWriter printwriter;
            private BufferedReader bufferedReader;

            //Following is the IP address of the chat server. You can change this IP address according to your configuration.
            // I have localhost IP address for Android emulator.
            private String CHAT_SERVER_IP = null;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_simple_client_server_chat);
                textField = (EditText) findViewById(R.id.editText1);
                button = (Button) findViewById(R.id.button1);
                textView = (TextView) findViewById(R.id.textView1);
                ipaddrs = (EditText) findViewById(R.id.ipaddrs);
                start = (Button) findViewById(R.id.start);

                start.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
###############// there client enter server public ip address via mobile app
                        CHAT_SERVER_IP = String.valueOf(ipaddrs.getText());
                        ChatOperator chatOperator = new ChatOperator();
                        chatOperator.execute();
                    }
                });



            }

            /**
             * This AsyncTask create the connection with the server and initialize the
             * chat senders and receivers.
             */
            private class ChatOperator extends AsyncTask<Void, Void, Void> {

                @Override
                protected Void doInBackground(Void... arg0) {
                    try {
                        client = new Socket(CHAT_SERVER_IP, 4444); // Creating the server socket.

                        if (client != null) {
                            printwriter = new PrintWriter(client.getOutputStream(), true);
                            InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
                            bufferedReader = new BufferedReader(inputStreamReader);
                        } else {
                            System.out.println("Server has not bean started on port 4444.");
                        }
                    } catch (UnknownHostException e) {
                        System.out.println("Faild to connect server " + CHAT_SERVER_IP);
                        e.printStackTrace();
                    } catch (IOException e) {
                        System.out.println("Faild to connect server " + CHAT_SERVER_IP);
                        e.printStackTrace();
                    }
                    return null;
                }

                /**
                 * Following method is executed at the end of doInBackground method.
                 */
                @Override
                protected void onPostExecute(Void result) {
                    button.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            final Sender messageSender = new Sender(); // Initialize chat sender AsyncTask.
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                messageSender.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                            } else {
                                messageSender.execute();
                            }
                        }
                    });

                    Receiver receiver = new Receiver(); // Initialize chat receiver AsyncTask.
                    receiver.execute();

                }

            }

            /**
             * This AsyncTask continuously reads the input buffer and show the chat
             * message if a message is availble.
             */
            private class Receiver extends AsyncTask<Void, Void, Void> {

                private String message;

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

                            if (bufferedReader.ready()) {
                                message = bufferedReader.readLine();
                                publishProgress(null);
                            }
                        } catch (UnknownHostException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException ie) {
                        }
                    }
                }

                @Override
                protected void onProgressUpdate(Void... values) {
                    textView.append("Server: " + message + "\n");
                }

            }

            /**
             * This AsyncTask sends the chat message through the output stream.
             */
            private class Sender extends AsyncTask<Void, Void, Void> {

                private String message;

                @Override
                protected Void doInBackground(Void... params) {
                    message = textField.getText().toString();
                    printwriter.write(message + "\n");
                    printwriter.flush();

                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    textField.setText(""); // Clear the chat box
                    textView.append("Client: " + message + "\n");
                }
            }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.menu_simple_client_server_chat, menu);
                return true;
            }



        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }
    }

当我输入服务器公共(public) IP 地址时,移动应用程序崩溃了。为什么会发生这种情况。如果我把本地IP地址放在那里,它就不会崩溃。

最佳答案

您必须在具有公共(public)IP的服务器上运行您的jar文件。您计算机上的地址是您的本地IP。此外,有时 WiFi 接入点可能会阻止端口 4444,例如在公共(public)场所(麦当劳、Edurom、肯德基等)。你必须记住这一点。

因此,使用公共(public)IP配置您自己的服务器,启动您的服务器

java -jar server.jar

然后测试一下。

例如,它是 Edurom(大学 WiFi)中可用端口的列表。就像我悲伤的那样,端口 4444 在这里被封锁了。 enter image description here

关于Java服务器android客户端通过不同网络进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31661258/

相关文章:

c - OpenSSL DTLS 连接从未建立

java - XML 到 JSON 的动态转换

java - 从自身中断线程

android - 具有三个 View 的水平 LinearLayout,中间 View 应水平居中

java - 如何在 Android 应用程序中保存天文钟耗时

android - 在 Android 中升级 OpenSSL

sockets - 使用 TUN/TAP 读取传入的数据,封装为 UDP 并传输

jquery - socket.on 调用其回调的次数过多

java - 如何处理 Java 中的网络连接问题

java - 用于 Java 应用程序的 Docker 镜像中的 Selenium