/** HelloWorld_Unicast 
 *
 *       The HyperCast HelloWorld programs demonstrate various aspects of
 *       the HyperCast API.  The programs create an overlay socket that 
 *       sends and receives messages. 
 *
 *       In HelloWorld_Unicast, the program receives multicast messages, extracts
 *       the source address, and sends a unicast message to the source of the message.
 *       The program assumes that there is another program that sends multicast messages.
 *       This file corresponds to an example program in the HyperCast API description 
 *       (see Chapter:  "API - The Basics", Section: "Sending Overlay Messages"). 
 *
 * @author HyperCast Team
 * @version 2005 (version 3.0)
 *
 */


import hypercast.*;

public class HelloWorld_Unicast implements I_ReceiveCallback {
	
	// The overlay socket 
	I_OverlaySocket MySocket = null;
	
	// The configuration object
	HyperCastConfig ConfObj = null;
	
	public static void main(String[] args) {
		
		// Create a new HelloWorld_CallBack instance 
		HelloWorld_Unicast hw = new HelloWorld_Unicast();
	}
	
	public void ReceiveCallback (I_OverlayMessage msg) {
		
		
		//	 Extract the payload and the logical address of the source
		byte[] data = msg.getPayload();
		String Src = msg.getSourceAddress().toString();
		

		// Print the payload (Skip messages sent by this program) 
		System.out.println("Received <"+ new String(data) + "> from logical address: " + Src + ".");
		
		// Manipulate payload a little and convert to message
		String  returnmsg = "Returned from " + Src + ": " +new String(data);
		byte[] MyData = returnmsg.getBytes();
		
		// Create a message
		I_OverlayMessage MyMessage = MySocket.createMessage(MyData);
		
		// Return payload as a unicast message 
		MySocket.sendToNode(MyMessage,msg.getSourceAddress());
		System.out.println(" message returned to source ...");
		
		/*		
		 * To send a unicast message to a  specific address (here: "500,500") 
		 * I_LogicalAddress dest = MySocket.createLogicalAddress("500,500");	
		 * MySocket.sendToNode(MyMessage, dest)
		 */
		
	}
	
	public  HelloWorld_Unicast () {
		
		//	Create a configuration object
		ConfObj = HyperCastConfig.createConfig("hypercast.xml");
		
		// Create an overlay socket with the configuration object
		MySocket=ConfObj.createOverlaySocket(this);
		
		// Join the overlay network 
		MySocket.joinOverlay();
		
		// Print the logical address */ 
		String MyLogicalAddress = MySocket.getLogicalAddress().toString();
		System.out.println("Logical address is " + MyLogicalAddress + ".");
		
	}
}