KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgroups > tests > ChannelTest


1 // $Id: ChannelTest.java,v 1.3 2004/07/30 04:44:51 jiwils Exp $
2

3 package org.jgroups.tests;
4
5
6 import org.jgroups.*;
7
8
9 /**
10  * Simple test - each instance broadcasts a message to the group and prints received messages to stdout.
11  * Start one instance, then another one. Both instances will receive each other's messages.
12  */

13 public class ChannelTest implements Runnable JavaDoc {
14     private Channel channel=null;
15     private Thread JavaDoc mythread=null;
16     private boolean looping=true;
17
18
19     public void start() throws Exception JavaDoc {
20         channel=new JChannel();
21         channel.connect("ExampleGroup");
22         mythread=new Thread JavaDoc(this);
23         mythread.start();
24         for(int i=0; i < 30; i++) {
25             System.out.println("Casting msg #" + i);
26             channel.send(new Message(null, null, "Msg #" + i));
27             Thread.sleep(1000);
28         }
29         channel.disconnect();
30         channel.close();
31         looping=false;
32         mythread.interrupt();
33         mythread.join(1000);
34     }
35
36
37     public void run() {
38         Object JavaDoc obj;
39         Message msg;
40         while(looping) {
41             try {
42                 obj=channel.receive(0); // no timeout
43
if(obj instanceof View)
44                     System.out.println("--> NEW VIEW: " + obj);
45                 else if(obj instanceof Message) {
46                     msg=(Message)obj;
47                     System.out.println("Received " + msg.getObject());
48                 }
49             }
50             catch(ChannelNotConnectedException conn) {
51                 break;
52             }
53             catch(Exception JavaDoc e) {
54                 System.err.println(e);
55             }
56         }
57     }
58
59
60     public static void main(String JavaDoc args[]) {
61         ChannelTest test;
62         try {
63             test=new ChannelTest();
64             test.start();
65         }
66         catch(Exception JavaDoc e) {
67             System.err.println(e);
68         }
69     }
70
71 }
72
Popular Tags