next up previous contents
Next: Synchronous Group Message Call Up: Channel Previous: EnsChannel

Example

The code below shows a simple example of how an EnsChannel is used:

public class ChannelTest implements Runnable {
    private Channel channel=null;
    private String  props="Top:Heal:Switch:Leave:Inter:Intra:Elect:"+
                          "Merge:Sync:Suspect:Top_appl:Pt2ptw:"+
                          "Pt2pt:Frag:Stable:Mnak:Bottom";

    public void Start() throws Exception {
        channel=new EnsChannel("TestChannel", props);
        channel.Connect(3000);
        new Thread(this, "ChannelTestThread").start();
        for(int i=0; i < 10; i++) {
            channel.Cast(new String("This is msg #" + i).getBytes());
            Thread.currentThread().sleep(1000);
        }
        channel.Disconnect();
        channel.Destroy();
    }

    public void run() {
        while(true) {
            try {
                Message msg=channel.Receive(0); // no timeout
                System.out.println(new String(msg.GetBuffer()));
            }
            catch(NotConnected conn) {break;}
            catch(Exception e) {System.err.println(e);}
        }
    }

    public static void main(String args[]) {
        try {
            ChannelTest test=new ChannelTest();
            test.Start();
        }
        catch(Exception e) {System.err.println(e);}
    }   
}

First a new channels is created given a name and certain properties (used by Ensemble). Then the channel is connected (a wait of 3 seconds is added to let the channel discover other channels of the same name). The main part of the Start method sends 10 messages to all channels with the same name (i.e., the process group), waiting 1 second between sends, and finally disconnects from the channel and destroys it. Note that a separate thread is started to perform the task of receiving messages from the channel (remember, channels use the pull-style, so message have to be retrieved actively). When a message is received, its contents are converted into a string and printed on stdout.

For an example demonstrating the push-style see section 2.2.6.



Bela Ban
1998-08-06