溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

JGroups實(shí)現(xiàn)聊天小程序

發(fā)布時(shí)間:2020-10-08 13:43:23 來源:腳本之家 閱讀:156 作者:java_派大星 欄目:編程語言

本文實(shí)例為大家分享了JGroups實(shí)現(xiàn)聊天小程序的具體代碼,供大家參考,具體內(nèi)容如下

效果圖:

JGroups實(shí)現(xiàn)聊天小程序

代碼部分:

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();// 使用默認(rèn)的配置, udp.xml【YBXIANG:】該文件位于jgroups-x.y.z.Final.jar中。
 channel.setReceiver(this);//注冊(cè)一個(gè) 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) {
 }
 }
 }
 
 //如果有節(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<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實(shí)現(xiàn)聊天小程序

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI