JGroups实现聊天小程序
程序员文章站
2024-02-16 22:34:52
本文实例为大家分享了jgroups实现聊天小程序的具体代码,供大家参考,具体内容如下
效果图:
代码部分:
package com.lei.jgoups;...
本文实例为大家分享了jgroups实现聊天小程序的具体代码,供大家参考,具体内容如下
效果图:
代码部分:
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); } } }
架包:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。