/** HelloWorld_CallBack 
 *
 *       The HyperCast HelloWorld programs demonstrate various aspects of
 *       the HyperCast API.  The programs create an overlay socket that 
 *       sends and receives messages. 
 *
 *       In HelloWorld_CallBack, all receive operations are nonblocking.
 *       This file corresponds to an example program in the HyperCast API description 
 *       (see Chapter:  "API - The Basics", Section: "The HelloWorld program"). 
 * 
 *       The file is a bit more complex than the example in the chapter.
 *
 * @author HyperCast Team
 * @version 2005 (version 3.0)
 *
 */


import hypercast.*;

public class HelloWorld_CallBack implements I_ReceiveCallback {
	
// The string we send 
String MyString = new String("Hello World");

// 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_CallBack hw = new HelloWorld_CallBack();
}

    
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) 
        if(!msg.getSourceAddress().equals(MySocket.getLogicalAddress()))
            System.out.println("Received <"+ new String(data) + "> from logical address: " + Src + ".");
	  }
		
public  HelloWorld_CallBack () {
	
	//	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 + ".");
	
	// Repeat forever
	for(int i=1;i<100;i++) {

		// wait 2 seconds 	
		try {
	        Thread.sleep(2000);
		} catch (InterruptedException e) {}	
		
		// Convert the string to a byte array and create a message
		byte[] MyData = MyString.getBytes(); 
		I_OverlayMessage MyMessage = MySocket.createMessage(MyData);

		// The message is sent to all members of the overlay //
		MySocket.sendToAll(MyMessage);
		System.out.println(" message sent to other members ...");
	 }
	MySocket.closeSocket();
}
}