我需要打开 N 个多播套接字(其中 N 来自参数列表的大小)。然后,我将在一个循环中将相同的数据发送到 N 个套接字中的每一个,最后关闭每个套接字。我的问题是,如何使用 try-with-resources 块执行此操作?以下是我将如何使用单个资源执行此操作:
final int port = ...;
try (final MulticastSocket socket = new MulticastSocket(port)) {
// Do a bunch of sends of small packet data over a long period of time
...
}
我能想到的使用多个端口执行此操作的唯一方法如下:
final List<Integer> ports = ...;
final List<MulticastSocket> sockets = new ArrayList<>(ports.size());
try {
for (final Integer port : ports) {
sockets.add(new MulticastSocket(port));
}
// Do a bunch of sends of small packet data over a long period of time
...
} finally {
for (final MulticastSocket socket : sockets) {
try {
socket.close();
} catch (final Throwable t) {
// Eat the exception
}
}
}
有没有更简洁的方法来实现这一点,或者我提出的解决方案是否尽可能好?