import java.net.DatagramPacket; import java.net.InetAddress; import…
- User
import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
public class MulticastListener implements Runnable{
codeprivate String multicastIP; private int multicastPort; private BlockingQueue<String> notificationsQueue; private int notifyTimeout; public MulticastListener(String multicastIP, int multicastPort, BlockingQueue<String> notificationsQueue, int notifyTimeout) { this.multicastIP = multicastIP; this.multicastPort = multicastPort; this.notificationsQueue = notificationsQueue; this.notifyTimeout = notifyTimeout; } public void run() { byte[] buffer = new byte[1024]; try (MulticastSocket socket = new MulticastSocket(multicastPort)) { InetAddress group = InetAddress.getByName(multicastIP); socket.joinGroup(group); // imposto un timeout per controllare le notifiche socket.setSoTimeout(notifyTimeout); while (!Thread.currentThread().isInterrupted()) { DatagramPacket packet = new DatagramPacket(buffer, buffer.length); try { socket.receive(packet); String message = new String(packet.getData(), 0, packet.getLength()); notificationsQueue.put(message); } catch (SocketTimeoutException e) { // ignoro il timeout e riprovo } catch (InterruptedException e) { // catturo eccezione che potrebbe essere generata da notificationsQueue.put(message) (se la coda dovesse essere piena) Thread.currentThread().interrupt(); } } socket.leaveGroup(group); } catch (IOException e) { // catturo eccezione che potrebbe essere generata da socket.receive(packet) if (!Thread.currentThread().isInterrupted()) { System.err.println("IOException nel listener multicast: " + e.getMessage()); e.printStackTrace(); } } } - Assistant