(Android Studio)检查服务器状态

时间:2017-09-23 01:18:56

标签: java android server connection

我希望程序使用服务器ip +端口并检查它是否在线。现在我遇到了问题,程序显示我"离线"结果一直都是。 到目前为止我做了什么:

public void addEntry() {
        btn.setOnClickListener(
            new View.OnClickListener()
            {
                public void onClick(View view)
                {
                    String[] tmp = txt.getText().toString().split(":");
                    String ip = tmp[0];
                    int port = Integer.parseInt(tmp[1]);
                    Object[] params = {ip, port};
                    new Server().execute(params);
                }
            });
    }

    private class Server extends AsyncTask {
        @Override
        protected Object doInBackground(Object[] objects) {
            String ip = (String) objects[0];
            int port = (Integer) objects[1];


            boolean exists;

            try {
                SocketAddress sockaddr = new InetSocketAddress(ip, port);
                // Create an unbound socket
                Socket sock = new Socket();

                // This method will block no more than timeoutMs.
                // If the timeout occurs, SocketTimeoutException is thrown.
                int timeoutMs = 20000;   // 20 seconds (to be safe)
                sock.connect(sockaddr, timeoutMs);

                    exists = true;
                    sock.close();



            } catch(IOException e) {
                e.printStackTrace();
                exists = false;


            }
            return exists;
    }

        @Override
        protected void onPostExecute(Object o) {
            boolean result = (boolean) o;
            if (result) txt2.setText("online");
            else txt2.setText("offline");
        }
    }
}

我希望有人看到我的问题。提前谢谢。

0 个答案:

没有答案