Sunday, August 1, 2010

Reliable Multicasting with JGroups

Append the jgroups jar to your classpath.

Then execute the following code twice in different consoles like this.These are our chat clients.

java -Djava.net.preferIPv4Stack=true SimpleChat


import java.io.*;
import java.net.InetAddress;
import org.jgroups.*;

public class SimpleChat implements Receiver {
    JChannel channel;

    public static void main (String[] args) throws Exception {
        new SimpleChat ().start ();
    }

    private void start () throws Exception {
        channel = new JChannel ();
        channel.connect ("ChatCluster");
        channel.setReceiver (this);
        eventLoop ();
        channel.close ();
    }

    private void eventLoop () {
        BufferedReader in = new BufferedReader (new InputStreamReader (System.in));
        while ( true ) {
            try {
                System.out.print ("> ");
                System.out.flush ();
                String line = in.readLine ().toLowerCase ();
                if (line.startsWith ("quit") || line.startsWith ("exit")) {
                    break;
                }
                line = "[" + this + "] " + line;
                Message msg = new Message (null, null, line);
                channel.send (msg);
            } catch (Exception e) {
                e.printStackTrace ();
            }
        }
    }

    public void receive (Message message) {
        System.out.println ("message = " + new String (message.getBuffer ()));
    }

    public byte[] getState () {
        return new byte[0]; 
    }

    public void setState (byte[] bytes) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void viewAccepted (View view) {
        System.out.println ("view = " + view.toString ());
    }

    public void suspect (Address address) {
        System.out.println ("address = " + address);
    }

    public void block () {

    }
}

There are more fancy examples in there. Like org.jgroups.demos.Draw !

No comments:

Post a Comment