This code below demonstrates the implementation of a simple command-line
IRC client using JGroups: public class Chat extends ReceiverAdapter { private JChannel channel; public Chat(String props, String name) { channel = new JChannel(props) .setName(name) .setReceiver(this) .connect("ChatCluster"); } public void viewAccepted(View view) { System.out.printf("** view: %s\n", view); } public void receive(Message msg) { System.out.printf("from %s: %s\n", msg.getSource(), msg.getObject()); } private void send(String line) { try { channel.send(new Message(null, line)); } catch (Exception e) {} } public void run() throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.print("> "); System.out.flush(); send(in.readLine().toLowerCase()); } } public void end() throws Exception { channel.close(); } public static void start(Chat client) throws Exception { try { client.run(); } catch (Exception e) { } finally { client.end(); } } public static void main(String[] args) throws Exception { String props = "udp.xml"; String name; for (int i = 0; i A JChannel is instantiated from an XML configuration (e.g. ). The channel is the endpoint for joining a cluster. Next, the receiver is set, which means that two callbacks will be invoked: • when a new member joins, or an existing member leaves the cluster • when a message from some other cluster member is received Then, the channel joins cluster "ChatCluster". From now, messages can be sent and received, plus a new view (including this member) will be installed in all cluster members (including the newly joined member). Anything typed in the main loop results in the creation of a message to be sent to all cluster members, including the sender. Instances of the chat application can be run in the same process, on the same box, on different hosts in the local network, on hosts in different networks, or in the cloud. The code remains the same; only the configuration needs to be changed. For example, in a local network, IP multicasting might be used. When IP multicasting is disabled, TCP can be used as transport. When run in the cloud, TCP plus a cloud discovery protocol would be used and so on... ==Flexible protocol stack==