/** HelloWorldApp
 *
 *       The HyperCast HelloWorld programs demonstrate various aspects of
 *       the HyperCast API.  The programs create an overlay socket that
 *       sends and receives messages.
 *
 *       The HelloWorldApp program creates an overlay socket and joins an
 *       overlay network in the constructor. As a result, the program 
 *       is very short. 
 *       This file corresponds to an example program in the HyperCast API description
 *       (see Chapter:  "API - The Basics", Section: "The HyperCast Application").
 *
 * @author HyperCast Team
 * @version 2005 (version 3.0)
 *
 */

import hypercast.I_LogicalAddress;
import hypercast.I_OverlayMessage;
import hypercast.HyperCastException;
import hypercast.HyperCastAppl;

public class HelloWorldApp extends HyperCastAppl {

	// Called by HyperCast (socket adapter thread).
	// Extended from HyperCastAppl to handle incoming messages.
	public void ReceiveCallback (I_OverlayMessage message) {
		System.out.println(getLogicalAddress().toString() + ": Received \""
				+ new String(message.getPayload()) + "\" from "
				+ message.getSourceAddress().toString());

	}

	// The constructor creates an overlay socket that joins the overlay network 
	// The socket waits until it is stable and starts sending messages
	public HelloWorldApp(String cfile) {
		
		// This constructor creates an overlay socket that joins the overlay network 
		super(cfile); 
		
		// Block the program until the overlay socket has reached a "stable state" 
		// Note: The event NODE_ISSTABLE is not defined for all overlay protocols.

		waitUntil_NODE_ISSTABLE();
		System.out.println("HelloWorldApp: achieved stability.");

		// Transmit multicast messages forever 
		// Note: Different from some other programs, the message is created only once.
		byte[] messagePayload = "Hello World".getBytes();
		I_OverlayMessage message = createMessage(messagePayload);

		while (true) {
			sendToAll(message);
			System.out.println("Msg sent.");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
			}
		}
	}

	public static void main(String[] args) {

		new HelloWorldApp("hypercast.xml");
	}
}