1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.View;
import org.jgroups.util.Util;
import java.util.List;
import java.util.LinkedList;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SimpleChat extends ReceiverAdapter {
JChannel channel;
String user_name=System.getProperty("user.name", "n/a");
final List<String> state=new LinkedList<String>();
public void viewAccepted(View new_view) {
System.out.println("** view: " + new_view);
}
public void receive(Message msg) {
String line=msg.getSrc() + ": " + msg.getObject();
System.out.println(line);
synchronized(state) {
state.add(line);
}
}
public byte[] getState() {
synchronized(state) {
try {
return Util.objectToByteBuffer(state);
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
}
public void setState(byte[] new_state) {
try {
List<String> list=(List<String>)Util.objectFromByteBuffer(new_state);
synchronized(state) {
state.clear();
state.addAll(list);
}
System.out.println("received state (" + list.size() + " messages in chat history):");
for(String str: list) {
System.out.println(str);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
private void start() throws Exception {
channel=new JChannel();
channel.setReceiver(this);
channel.connect("ChatCluster");
channel.getState(null, 10000);
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="[" + user_name + "] " + line;
Message msg=new Message(null, null, line);
channel.send(msg);
}
catch(Exception e) {
}
}
}
public static void main(String[] args) throws Exception {
new SimpleChat().start();
}
}
|