本文實(shí)例為大家分享了JGroups實(shí)現(xiàn)聊天小程序的具體代碼,供大家參考,具體內(nèi)容如下
讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來(lái)自于我們對(duì)這個(gè)行業(yè)的熱愛(ài)。我們立志把好的技術(shù)通過(guò)有效、簡(jiǎn)單的方式提供給客戶,將通過(guò)不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長(zhǎng)期合作伙伴,公司提供的服務(wù)項(xiàng)目有:域名注冊(cè)、虛擬主機(jī)、營(yíng)銷軟件、網(wǎng)站建設(shè)、臺(tái)安網(wǎng)站維護(hù)、網(wǎng)站推廣。效果圖:
代碼部分:
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 Liststate=new LinkedList (); public static void main(String[] args) throws Exception { new SimpleChat().start(); } private void start() throws Exception { channel=new JChannel();// 使用默認(rèn)的配置, udp.xml【YBXIANG:】該文件位于jgroups-x.y.z.Final.jar中。 channel.setReceiver(this);//注冊(cè)一個(gè) Receiver 來(lái)接收消息并查看變化 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) { } } } //如果有節(jié)點(diǎn)加入后會(huì)回調(diào)此函數(shù) public void viewAccepted(View new_view) { System.out.println("** view: " + new_view); } //接收到消息后會(huì)調(diào)用此函數(shù) public void receive(Message msg) { String line=msg.getSrc() + ": " + msg.getObject(); System.out.println(line); synchronized(state) {//同步調(diào)用 state.add(line); } } //getState回調(diào)方法 public void getState(OutputStream output) throws Exception { synchronized(state) { Util.objectToStream(state, new DataOutputStream(output)); } } // 從input stream中讀取狀態(tài),然后做相應(yīng)的設(shè)置: public void setState(InputStream input) throws Exception { List list; list=(List )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); } } }