亲宝软件园·资讯

展开

JGroups实现聊天小程序 JGroups实现聊天小程序

java_派大星 人气:0

效果图:

代码部分:

package com.lei.jgoups;
 
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
 
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.View;
import org.jgroups.util.Util;
 
public class SimpleChat extends ReceiverAdapter{
 JChannel channel;
 String user_name=System.getProperty("user.name", "n/a");
 final List<String> state=new LinkedList<String>();
 public static void main(String[] args) throws Exception {
 new SimpleChat().start();
 }
 private void start() throws Exception {
 channel=new JChannel();// 使用默认的配置, udp.xml【YBXIANG:】该文件位于jgroups-x.y.z.Final.jar中。
 channel.setReceiver(this);//注册一个 Receiver 来接收消息并查看变化
 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, line);
 channel.send(msg);
 }
 catch(Exception e) {
 }
 }
 }
 
 //如果有节点加入后会回调此函数
 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);
 }
 }
 
 //getState回调方法
 public void getState(OutputStream output) throws Exception {
 synchronized(state) {
 Util.objectToStream(state, new DataOutputStream(output));
 }
 }
 
 // 从input stream中读取状态,然后做相应的设置:
 public void setState(InputStream input) throws Exception {
 List<String> list;
 list=(List<String>)Util.objectFromStream(new DataInputStream(input));
 synchronized(state) {
 state.clear();
 state.addAll(list);
 }
 System.out.println(list.size() + " messages in chat history):");
 for(String str: list) {
 System.out.println(str);
 }
 }
}

架包:

加载全部内容

相关教程
猜你喜欢
用户评论