// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package jcademo.raoutbound.udp;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

public class UDPMultiPlexer {
	// singleton
	private static UDPMultiPlexer instance = new UDPMultiPlexer();
	public static UDPMultiPlexer getInstance() {
		return instance;
	}
	// data
	private InetAddress addr;
	private int port;
	private DatagramSocket dgs;
	private Map<String, BlockingQueue<String>> qmap = new HashMap<String, BlockingQueue<String>>();
	// connect
	public void associate(String host, int port) throws IOException {
		addr = InetAddress.getByName(host);
		this.port = port;
		dgs = new DatagramSocket();
	}
	// register receive queue
	public void register(String id, BlockingQueue<String> q) {
		synchronized(qmap) {
			qmap.put(id, q);
		}
	}
	// send
	public void send(String id, String line) throws IOException {
		UDPUtil.send(dgs, new UDPUtil.DataAndDestination(id + "\r\n" + line, addr, port));
	}
	// deregister receive queue
	public void deregister(String id) {
		synchronized(qmap) {
			qmap.remove(id);
		}
	}
	// close
	public void close() throws IOException {
		dgs.close();
	}
	// receive loop that put responses in correct queue
	public void receive() throws IOException, InterruptedException {
		while(true) {
			UDPUtil.DataAndDestination dad = UDPUtil.receive(dgs);
			String[] parts = dad.getData().split("\r\n");
			String id = parts[0];
			String line = parts[1];
			qmap.get(id).put(line);
		}
	}
}
