/** StreamReceiver
 *
 *       The HyperCast HelloWorld programs demonstrate various aspects of
 *       the HyperCast API.  The programs create an overlay socket that 
 *       sends and receives messages. 
 *
 *       The StreamReceiver is the  companion program to the StreamSender.
 *       The program accepts an input stream and reads data from it. 
 *       This file corresponds to an example program in the HyperCast API description 
 *       (see Chapter:  "API - Advanced Topics", Section 3.2: "Stream API"). 
 * 
 *       The file is a bit more complex than the example in the chapter.
 *
 * @author HyperCast Team
 * @version August 2006
 *
 */


import hypercast.*;

public class StreamReceiver  {
	
	
	//	The overlay socket 
	I_OverlaySocket MySocket = null;
	
	//	The configuration object
	HyperCastConfig ConfObj = null;
	
	// Input stream for receiving data from overlay
	HCastInputStream in = null;
	
	public static void main(String[] args) {
		
	// Create a new HelloWorld_CallBack instance 
		StreamReceiver hw = new StreamReceiver();
	}
	
	public  StreamReceiver () {
		
		//	Create a configuration object
		ConfObj = HyperCastConfig.createConfig("hypercast.xml");
		
		// Create an overlay socket with the configuration object
		MySocket=ConfObj.createOverlaySocket(null);
		
		// Join the overlay network 
		MySocket.joinOverlay();
		
		// Print the logical address */ 
		String MyLogicalAddress = MySocket.getLogicalAddress().toString();
		System.out.println("Logical address is " + MyLogicalAddress + ".");
		
		// Create a stream manager
		StreamManager MyStreams =  MySocket.getStreamManager();
		
		// Create an input stream with identifier "1111" 
		try {
			System.out.println("Waiting for stream.");
			in = MyStreams.acceptInputStream();		
			System.out.println("Stream accepted.");
			
			// setSoTimeout limits the waiting time of a read()
			in.setSoTimeout(5000);
		} catch (Exception e){};
		
		// Read data byte-by-byte until no data is available.
		int MsgSize=0;
		byte[] byteBuffer = new byte [1];
		while (MsgSize != -1) {
			try {
				MsgSize  = in.read(byteBuffer);					
				System.out.print(new String(byteBuffer));	
			} catch (Exception e){};
		}
		System.out.println("No more data. Closing socket.");
		MySocket.closeSocket();
	}
}