检查服务器是否已启动无一例外 [英] Check if Server is up without exception

查看:136
本文介绍了检查服务器是否已启动无一例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查,如果某个IP端口是用于Java的Andr​​oid应用程序打开。

I would like to check if a certain IP-Port is open in Java for an android application.

这是code调用:

 button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                RetreiveFeedTask Check=new RetreiveFeedTask();
                try{
                Work=(Check.execute(Exec, ServerIP, ServerPort)).get();
                ALL.setText(Work);//Display what is returned
                }
                catch(Exception e)
                {e.printStackTrace(); }
                if(Work.equal("xyz")
                {
                    //Do Stuff
                }
                else 
                {
                                     //Do Other Stuff
                }

            }
        });

异步code:

class RetreiveFeedTask extends AsyncTask<String , String , String > {

    //private Exception e;
    String GotBack="3";

    @Override
    protected String doInBackground(String... params) {
        try{        
        Socket s= new Socket(params[1], Integer.parseInt(params[2]));
        s.close();
        }
        catch(Exception e){e.printStackTrace(); return "3";}


        try{ 
                Socket socket = new Socket(params[1], Integer.parseInt(params[2]));  
                PrintWriter output = new PrintWriter(socket.getOutputStream());    
                BufferedReader input=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                output.println(params[0]);
                output.flush();
                String read="";
                while((read=input.readLine())!=null)
                {
                GotBack=read;

                }

                socket.close();
                }
            catch(SocketException e){e.printStackTrace(); }
            catch(Exception e){e.printStackTrace();}

        return GotBack;
    }
}

目前,该按钮冻结时,我美元,它p $ PSS ...

Currently, the button freezes when I press on it...

我检查,如果{ServerIP1-ServerPort1}接受连接,如果不是我需要知道的。

I check if {ServerIP1-ServerPort1} accepts connections, if not I need to know.

推荐答案

我假设你打电话给你的AsyncTask两次,第一次与普通服务器和第二次与备份服务器。现在试试这个,开始你的AsyncTask同时指定服务器和两个端口,即
BackgroundTask(NrmSrvAddress,NrmSrvPort,bckSrvAddress,bckSrvPort);
然后用下面的函数来连接到服务器(S):
(我还没有运行code,它只是一个想法)

I assumed that you call your Asynctask twice, first with the normal server and a second time with the backup server. Now try this, and start your AsyncTask specifying both servers and both ports, i.e. BackgroundTask(NrmSrvAddress, NrmSrvPort, bckSrvAddress, bckSrvPort); Then use the following function to connect to the server(s): (I have not run the code, it's just an idea)

public Socket ConnectToServer(String normalSrv, int nrmPort, String backupSrv, int bckPort)
{
    // Let's try to connect to the Normal Server first.
    try
    {
        Socket retSocket = new Socket();
        InetAddress addr = InetAddress.getByName(normalSrv);
        SocketAddress sockaddr = new InetSocketAddress(addr, nrmPort);
        retSocket.connect(sockaddr, 30000); // 30 seconds timeout
        return retSocket;
    }
    catch (Exception e)
    {
        // can't connect to the Normal Server
        e.printStackTrace();
    }

    // Normal server is down, let's try to connect to the Backup Server.
    try
    {
        Socket retSocket = new Socket();
        InetAddress addr = InetAddress.getByName(backupSrv);
        SocketAddress sockaddr = new InetSocketAddress(addr, bckPort);
        retSocket.connect(sockaddr, 30000); // 30 seconds timeout
        return retSocket;
    }
    catch (Exception e)
    {
        // can't connect to the Backup Server
        e.printStackTrace();
    }
    // none of the server are available
    return null;
}

// Then, in your AsyncTask:
@Override
protected String doInBackground(String... params) {

    Socket socket = ConnectToServer(params[1], Integer.parseInt(params[2]), params[3], Integer.parseInt(params[4]));
    if (socket != null) 
    {
        try{ 
               PrintWriter output = new PrintWriter(socket.getOutputStream());    
               BufferedReader input=new BufferedReader(new InputStreamReader(socket.getInputStream()));
               output.println(params[0]);
               output.flush();
               String read="";
               while((read=input.readLine())!=null)
               {
                  TheData=read;
               }
            }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally 
        { 
            socket.close();                                                 
        }
        return TheData;

哦,我明白了,你尝试在onclick事件执行的AsyncTask,并希望在主线程等待,直到它完成?这不是使用的AsyncTask的方式。您应该使用的AsyncTask的onPostExecute方法来处理返回值。这就是为什么你的按钮冻结。

Oh, I see, you try to execute an AsyncTask in the OnClick event and want the Main thread to wait until it's finished? That's not the way AsyncTask are used. You should use the onPostExecute method of the AsyncTask to process the return value. That's why your button freezes.

我可以建议如下:


  1. 创建按钮的onClick事件的新线程。如果你想反正用的AsyncTask去的话,阅读它,它是如何工作的。

  1. Create a new thread in the button's OnClick event. If you want to go with AsyncTask anyway, then read about it and how it works.

在该线程(或后台进程)试图连接到正常服务器,如果它失败尝试备份服务器。

In that thread (or background process) try to connect to the "normal server" and if it's fails try the backup server.

的主要思想是在code IConnectToServer之前发布的,你要的部分,第一个尝试,而不是返回套接字连接到正常的服务器,并返回它得到的插座,只是做阅读在那里。如果连接失败,然后做同样的备份服务器的一部分。

The main idea is on the code I posted before "ConnectToServer", you have to parts, first one try to connect to the normal server and return the socket it gets, instead of returning the socket just do the reading right there. If it fails to connect then do the same on the part of the backup server.

这篇关于检查服务器是否已启动无一例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆