1 package org.jgroups.tests; 2 3 import org.jgroups.*; 4 import org.jgroups.util.Util; 5 6 import java.io.Serializable ; 7 8 14 public class DiscoveryTest { 15 Channel ch; 16 17 public static void main(String [] args) throws Exception { 18 String props=null; 19 20 for(int i=0; i < args.length; i++) { 21 if(args[i].equals("-props")) { 22 props=args[++i]; 23 continue; 24 } 25 System.out.println("DiscoveryTest [-props <properties>]"); 26 } 27 28 new DiscoveryTest().start(props); 29 } 30 31 private void start(String props) throws Exception { 32 ch=new JChannel(props); 33 ch.connect("discovery"); 34 35 new Thread () { 36 public void run() { 37 while(true) { 38 try { 39 ch.send(null, null, new Data(Data.DISCOVERY_REQ, null)); 40 } 41 catch(ChannelNotConnectedException e) { 42 e.printStackTrace(); 43 } 44 catch(ChannelClosedException e) { 45 e.printStackTrace(); 46 } 47 Util.sleep(5000); 48 } 49 } 50 }.start(); 51 52 Object obj; 53 Data d; 54 Message msg; 55 while(ch.isConnected()) { 56 obj=ch.receive(0); 57 if(obj instanceof Message) { 58 msg=(Message)obj; 59 d=(Data)msg.getObject(); 60 switch(d.type) { 61 case Data.DISCOVERY_REQ: 62 ch.send(msg.getSrc(), null, new Data(Data.DISCOVEY_RSP, 63 " my address is " + ch.getLocalAddress())); 64 break; 65 case Data.DISCOVEY_RSP: 66 Address sender=msg.getSrc(); 67 68 System.out.println("received response from " + sender + ": " + d.payload); 69 break; 70 default: 71 System.err.println("type " + d.type + " not known"); 72 break; 73 } 74 } 75 } 76 ch.close(); 77 } 78 79 80 private static class Data implements Serializable { 81 private static final int DISCOVERY_REQ = 1; 82 private static final int DISCOVEY_RSP = 2; 83 private static final long serialVersionUID = 9193522684840201133L; 84 85 int type=0; 86 Serializable payload=null; 87 88 89 public Data(int type, Serializable payload) { 90 this.type=type; 91 this.payload=payload; 92 } 93 94 } 95 } 96 | Popular Tags |