/** StreamSender
 *
 *       The HyperCast HelloWorld programs demonstrate various aspects of
 *       the HyperCast API.  The programs create an overlay socket that 
 *       sends and receives messages. 
 *
 *       The StreamSender uses the StreamManager of the HyperCast API, which  
 *       supports the byte-oriented streams programming abstraction of the 
 *       Java I/O package. 
 *       The StreamSender creates an output stream and writes data to the stream. 
 *       The companion program, the StreamReceiver, reads the data and displays 
 *       the output. 
 *       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 StreamSender  {
	
	//	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 
		StreamSender hw = new StreamSender();
	}
	
	
	public  StreamSender () {
		
		//	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 output stream with identifier "1111" 
		short streamID = 1111;
		HCastOutputStream out =  MyStreams.getOutputStream(streamID);
		
		for (int i = 0;i<100;i++) {
			
			// wait 2 seconds 	
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {}	;
			
			// Modify the string 
			String str =  streamID + "-" + i + ": "+ MyString + "\n";
			byte[] byteBuffer = str.getBytes(); 
			
			// Write string 
			try {
				out.write(byteBuffer); 
			} catch (Exception e){}
			System.out.println("Sent: "+ new String(byteBuffer));
		}
		
		// Clean up and close socket. 
		try {
			out.flush();
		} catch (Exception e){};
		
		MySocket.closeSocket();
	}
}