本文實例為大家分享了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); } } }
文章名稱:JGroups實現聊天小程序-創新互聯
URL分享:http://www.yijiale78.com/article16/csipgg.html
成都網站建設公司_創新互聯,為您提供移動網站建設、建站公司、網站制作、App開發、小程序開發、域名注冊
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯