1 3 4 package org.jgroups.tests; 5 6 import org.jgroups.JChannel; 7 import org.jgroups.Message; 8 import org.jgroups.stack.IpAddress; 9 10 import java.io.BufferedReader ; 11 import java.io.InputStreamReader ; 12 13 14 18 public class UnicastChannelTest { 19 boolean server=false; 20 String host="localhost"; 21 int port=0; 22 String props=null; 23 JChannel ch; 24 25 26 public void start(String [] args) throws Exception { 27 28 for(int i=0; i < args.length; i++) { 29 String tmp=args[i]; 30 31 if("-server".equals(tmp)) { 32 server=true; 33 continue; 34 } 35 36 if("-props".equals(tmp)) { 37 props=args[++i]; 38 continue; 39 } 40 41 if("-host".equals(tmp)) { 42 host=args[++i]; 43 continue; 44 } 45 46 if("-port".equals(tmp)) { 47 port=Integer.parseInt(args[++i]); 48 continue; 49 } 50 51 help(); 52 return; 53 } 54 55 56 57 if(server) { 58 runServer(); 59 } 60 else { 61 runClient(); 62 } 63 64 } 65 66 void runClient() throws Exception { 67 IpAddress addr; 68 Message msg; 69 Object obj; 70 String line; 71 BufferedReader reader; 72 73 ch=new JChannel(props); 74 ch.connect(null); 76 addr=new IpAddress(host, port); 77 reader= new BufferedReader (new InputStreamReader (System.in)); 78 79 while(true) { 80 System.out.print("> "); 81 line=reader.readLine(); 82 if(line.startsWith("quit") || line.startsWith("exit")) { 83 ch.close(); 84 return; 85 } 86 msg=new Message(addr, null, line); 87 ch.send(msg); 88 while((obj=ch.peek(1000)) != null) { 89 obj=ch.receive(1000); 90 if(obj == null) 91 break; 92 if(!(obj instanceof Message)) { 93 System.out.println("<-- " + obj); 94 } 95 else { 96 System.out.println("<-- " + ((Message)obj).getObject()); 97 } 98 } 99 } 100 } 101 102 void runServer() throws Exception { 103 Object obj; 104 Message msg, rsp; 105 106 ch=new JChannel(props); 107 ch.connect(null); System.out.println("server started at " + new java.util.Date () + 109 ", listening on " + ch.getLocalAddress()); 110 while(true) { 111 obj=ch.receive(0); 112 if(!(obj instanceof Message)) { 113 System.out.println(obj); 114 } 115 else { 116 msg=(Message)obj; 117 System.out.println("-- " + msg.getObject()); 118 rsp=new Message(msg.getSrc(), null, "ack for " + msg.getObject()); 119 ch.send(rsp); 120 } 121 } 122 } 123 124 void help() { 125 System.out.println("UnicastChannelTest [-help] [-server] [-props <props>]" + 126 "[-host <host>] [-port <port>]"); 127 } 128 129 130 public static void main(String [] args) { 131 try { 132 new UnicastChannelTest().start(args); 133 } 134 catch(Exception ex) { 135 ex.printStackTrace(); 136 } 137 } 138 139 } 140 | Popular Tags |