本文实例为大家分享了jgroups实现 聊天 小程序 的具体代码,供大家参考,具体内容如下
效果图:
代码部分:
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 |
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); } } } |
架包:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://blog.csdn.net/junmoxi/article/details/78424426