简体   繁体   English

如何使用后台线程检查套接字是否已连接

[英]How to check if socket is connected or not using background thread

i am developing application in which i am checking availability of port before reading and writing on socket. 我正在开发的应用程序,其中我在套接字上读写之前检查端口的可用性。 i am using following code to check status 我正在使用以下代码检查状态

private boolean isAvailable(String host, int port) {
        try {
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(host, port), 1000);
            isPortAvailable = socket.isConnected();
        } catch (IOException e) {
            isPortAvailable = false;
        }
        return isPortAvailable;
    }

After this i am checking this status on onClick() 之后,我在onClick()上检查此状态

if (isAvailable(ip, Integer.parseInt(portLVR))) {
    startActivity(new Intent(getApplicationContext(),ActivityLivingRoom.class));
} else
    Toast.makeText(getApplicationContext(),"Connection Error !", Toast.LENGTH_SHORT).show();

but my problem is if i check this status on main thread then android will give me networkonMainThradException so how do i manage this operation using background thread? 但我的问题是,如果我在主线程上检查此状态,那么android将给我networkonMainThradException所以我如何使用后台线程管理此操作?

Try this 尝试这个

 private class SocketCheckTask extends AsyncTask<String , Integer , Boolean> {
       String classname="";
     public SocketCheckTask (String classname) {
              this.classname=classname;
    } 
@Override
protected Boolean doInBackground(String... params) {
    return isAvailable(params[0], Integer.parseInt(params[1]);
  }

@Override
protected void onPostExecute(Boolean isAvailable) {
   if (isAvailable)) {
     Class c=Class.forName("yourpackage"+classname);
startActivity(new Intent(getApplicationContext(),c));
     } else
Toast.makeText(getApplicationContext(),"Connection Error !", Toast.LENGTH_SHORT).show();
     }
}

And send it like this 像这样发送

 SocketCheckTask task=new SocketCheckTask ("ActivityLivingRoom");
task.execute(ipadress,port);

Like this: 像这样:

private class CheckAvailabilityTask extends AsyncTask<Void, Void, Boolean> {
    String ip;
    int port;

    public CheckAvailabilityTask(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }
    @Override
    protected Boolean doInBackground(Void... params) {
        return isAvailable(this.ip, this.port);
    }

    @Override
    protected void onPostExecute(Boolean isAvailable) {
        if (iisAvailable) {
            startActivity(new Intent(getApplicationContext(),ActivityLivingRoom.class));
        } else
        Toast.makeText(getApplicationContext(),"Connection Error !", Toast.LENGTH_SHORT).show();
    }
}

And in onClick() event: onClick()事件中:

new CheckAvailabilityTask(IP, PORT).execute();

I think best solution would be, start a new thread on click event and putting your start activity code inside the same thread. 我认为最好的解决方案是在click事件上启动一个新线程,然后将您的启动活动代码放入同一线程中。

If you are using toast you can do it from that thread but if you plan to update UI (like red/green status) you have to use handler and messages. 如果您正在使用Toast,则可以从该线程中进行操作,但是如果您打算更新UI(如红色/绿色状态),则必须使用处理程序和消息。

FYI, Asynctask just remove the implementation of Thread and shows people a nice abstraction. 仅供参考,Asynctask只是删除了Thread的实现,并向人们展示了一个不错的抽象。

You can't open a socket and never close it just to establish whether a host:port is available. 您无法打开套接字,也永远无法关闭套接字,只是为了确定host:port是否可用。

The only real way to test whether any service or resource is available is to try to use it. 测试任何服务或资源是否可用的唯一真实方法是尝试使用它们。

Just do the connect, and the I/O, when you need to do them, and handle the resulting exceptions at that point. 只需在需要时进行连接和I / O,然后处理由此产生的异常。 You have to catch them anyway. 无论如何,您都必须抓住它们。

Don't write code that tries to predict the future. 不要编写试图预测未来的代码。

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

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