[wpiutil] Add WPICleaner and an example how to use it (#4850)

This commit is contained in:
Thad House
2023-07-10 09:59:36 -07:00
committed by GitHub
parent 7a099cb02a
commit e5452e3f69
3 changed files with 48 additions and 2 deletions

View File

@@ -4,11 +4,18 @@
package edu.wpi.first.net;
import edu.wpi.first.util.WPICleaner;
import java.lang.ref.Cleaner.Cleanable;
import java.util.Map;
/** Class to announce over mDNS that a service is available. */
public class MulticastServiceAnnouncer implements AutoCloseable {
private final int m_handle;
private final Cleanable m_cleanable;
private static Runnable cleanupAction(int handle) {
return () -> WPINetJNI.freeMulticastServiceAnnouncer(handle);
}
/**
* Creates a MulticastServiceAnnouncer.
@@ -24,6 +31,7 @@ public class MulticastServiceAnnouncer implements AutoCloseable {
String[] values = txt.values().toArray(String[]::new);
m_handle =
WPINetJNI.createMulticastServiceAnnouncer(serviceName, serviceType, port, keys, values);
m_cleanable = WPICleaner.register(this, cleanupAction(m_handle));
}
/**
@@ -36,11 +44,12 @@ public class MulticastServiceAnnouncer implements AutoCloseable {
public MulticastServiceAnnouncer(String serviceName, String serviceType, int port) {
m_handle =
WPINetJNI.createMulticastServiceAnnouncer(serviceName, serviceType, port, null, null);
m_cleanable = WPICleaner.register(this, cleanupAction(m_handle));
}
@Override
public void close() {
WPINetJNI.freeMulticastServiceAnnouncer(m_handle);
m_cleanable.clean();
}
public void start() {

View File

@@ -4,9 +4,17 @@
package edu.wpi.first.net;
import edu.wpi.first.util.WPICleaner;
import java.lang.ref.Cleaner.Cleanable;
/** Class to resolve a service over mDNS. */
public class MulticastServiceResolver implements AutoCloseable {
private final int m_handle;
private final Cleanable m_cleanable;
private static Runnable cleanupAction(int handle) {
return () -> WPINetJNI.freeMulticastServiceResolver(handle);
}
/**
* Creates a MulticastServiceResolver.
@@ -15,11 +23,12 @@ public class MulticastServiceResolver implements AutoCloseable {
*/
public MulticastServiceResolver(String serviceType) {
m_handle = WPINetJNI.createMulticastServiceResolver(serviceType);
m_cleanable = WPICleaner.register(this, cleanupAction(m_handle));
}
@Override
public void close() {
WPINetJNI.freeMulticastServiceResolver(m_handle);
m_cleanable.clean();
}
public void start() {