简体   繁体   English

自动刷新Java中连接的IP地址列表

[英]Automatically refresh a list of IP Addresses connected in Java

I'm writing some code that sends/receives information from computers connected to the same network. 我正在编写一些代码,用于从连接到同一网络的计算机发送/接收信息。 I have a method that gets the IP of the online computers at that exact moment, but I need to refresh the list when a new IP appears/disappears. 我有一种方法可以在那一刻获取在线计算机的IP,但是当新IP出现/消失时,我需要刷新列表。

I don't think having a thread and while (true) calling the method is the best solution. 我不认为拥有线程, while (true)调用该方法是最佳解决方案。 And I can't think of anything else - any suggestions? 我想不出什么了-有什么建议吗?

Here is the sample of the code I use to search for active computers on the network: 这是我用来搜索网络上活动计算机的代码示例:

public List<String> searchApps() {
    List<AddressServiceTypePair> ip = this.networkController.getDiscovered();  //returns an ArrayList<AddressServiceTypePair>

    onlineApps.clear();
    for (AddressServiceTypePair service : ip) {
        onlineApps.add(service);
    }

    List<String> list = new ArrayList<>();
    for (AddressServiceTypePair aux : onlineApps) {
        list.add(aux.getIP());
    }
    return list;
}

It is difficult to generalize based on the unclear code sample posted. 很难根据所发布的不清楚的代码示例进行概括。 However, I'm assuming you are writing some type of client and server code. 但是,我假设您正在编写某种类型的客户端和服务器代码。 There is no simple way to be notified of an added/removed computer on the network. 没有简单的方法可以通知网络上添加/删除的计算机。 I would be surprised if you needed an up-to-the- moment list of IPs. 如果你需要IP地址的先进的the- 时刻列表我会感到很惊讶。 You could put your IP-discovering method in an infinite loop and simply include Thread.sleep(milliseconds); 您可以将IP发现方法置于无限循环中,只需包含Thread.sleep(milliseconds); in your loop. 在你的循环中。

If you really do need extremely up-to-date information, you could have each connected computer also connect to a Socket on another port in a separate thread, then try to read from the Socket - that way you get an Exception as soon as the Socket closes. 如果您确实确实需要非常最新的信息,则可以使每台连接的计算机也通过单独的线程连接到另一个端口上的Socket,然后尝试从Socket读取-这样一来,您将获得Exception。套接字关闭。 You can add the IP of the client when the Socket is created, and your catch block can then update your list of active IPs when the Socket closes, signaling that client is no longer connected. 您可以在创建套接字时添加客户端的IP,然后,当套接字关闭时,catch块可以更新活动IP列表,这表明客户端已不再连接。

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

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