通过smack client + openfire server 实现 peer to peer communication

【0】README
1)本文旨在 给出源代码 实现 smack client + openfire server 实现 peer to peer communication
2)当然,代码中用到的 user 和 pass, 你需要事先在 openfire 里面注册;
3)also , you can checkout the source code  from   
https://github.com/pacosonTang/core-java-volume/tree/master/coreJavaSupplement/smack-client ;
Attention)要区分 ChatManagerListener and ChatMessageListener, 这两个监听器,它们的功能是不同的,但是长相却十分相似;



【2】代码如下 
package com.xmpp.client;import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Set;import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Message.Body;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.delay.packet.DelayInformation;// this class encapsulates some info for
// connection, login, creating chat.
public class UserChatBase { // smakc client base class.private XMPPTCPConnectionConfiguration conf;private AbstractXMPPConnection connection;private ChatManager chatManager;private Chat chat;/*** @param args refers to an array with ordered values as follows: user, password, host, port.*/public UserChatBase(String... args) {String username = args[0];String password = args[1];conf = XMPPTCPConnectionConfiguration.builder().setUsernameAndPassword(username, password).setServiceName(MyConstants.HOST).setHost(MyConstants.HOST).setPort(Integer.valueOf(MyConstants.PORT)).setSecurityMode(SecurityMode.disabled) // (attention of this line about SSL authentication.).build();connection = new XMPPTCPConnection(conf);chatManager = ChatManager.getInstanceFor(connection);// differentiation ChatManagerListener from ChatMessageListenerchatManager.addChatListener(new MyChatListener(this));}/*** connect to and login in openfire server.* @throws XMPPException * @throws IOException * @throws SmackException */public void connectAndLogin() throws SmackException, IOException, XMPPException {System.out.println("executing connectAndLogin method.");System.out.println("connection = " + connection);connection.connect();System.out.println("successfully connection.");connection.login(); // client logins into openfire server.System.out.println("successfully login.");}/*** disconnect to and logout from openfire server.* @throws XMPPException * @throws IOException * @throws SmackException */public void disconnect() {System.out.println("executing disconnect method.");try {connection.disconnect();} catch (Exception e) {e.printStackTrace();}}/*** create chat instance using ChatManager.*/public Chat createChat(String toUser) {		toUser += "@" + MyConstants.HOST;chat = chatManager.createChat(toUser);		// create the chat with specified user.(startup a thread)MessageHandler handler = new MessageHandler(chat); MessageHandler.Sender sender = handler.new Sender(); // creating inner class.new Thread(sender).start();// creating thread over.return chat;}/*** get chat timestamp, also time recoded when the msg starts to send.* @param msg * @return timestamp.*/public String getChatTimestamp(Message msg) {ExtensionElement delay = DelayInformation.from(msg);if(delay == null) {return null;}Date date = ((DelayInformation) delay).getStamp();DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);return format.format(date);}public XMPPTCPConnectionConfiguration getConf() {return conf;}public AbstractXMPPConnection getConnection() {return connection;}public ChatManager getChatManager() {return chatManager;}public Chat getChat() {return chat;}
}
package com.xmpp.client;import java.util.Locale;public class ClientA { // one client public static void main(String a[]) throws Exception {Locale.setDefault(Locale.CHINA);UserChatBase client = new UserChatBase(new String[]{"tangtang", "tangtang"});client.connectAndLogin();System.out.println("building connection between tangtang as sender and pacoson as receiver.");// create the chat with specified user.(startup a thread)client.createChat("pacoson");}
}
package com.xmpp.client;import java.util.Locale;public class ClientB { // another client.public static void main(String a[]) throws Exception {Locale.setDefault(Locale.CHINA);UserChatBase client = new UserChatBase(new String[]{"pacoson", "pacoson"});client.connectAndLogin();System.out.println("building connection between pacoson as sender and tangtang as receiver.");// create the chat with specified user.(startup a thread)client.createChat("tangtang");}
}
package com.xmpp.client;import java.util.Set;import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Message.Body;// 监听器
public class MyChatListener implements ChatManagerListener{private UserChatBase client;public MyChatListener(UserChatBase client) {this.client = client;}@Overridepublic void chatCreated(Chat chat, boolean createdLocally) {if (!createdLocally) {chat.addMessageListener(new ChatMessageListener() {@Overridepublic void processMessage(Chat chat, Message message) {String from = message.getFrom();Set<Body> bodies = message.getBodies();String timestamp = client.getChatTimestamp(message);if(timestamp != null) {System.out.println(timestamp);}for(Body b : bodies) {System.out.println(from + ":" + b.getMessage());}}});}}
}
package com.xmpp.client;public class MyConstants { // 常量类public static final int PORT = 5222;public static final String HOST = "lenovo-pc";public static final String PLUGIN_PRESENT_URL= "http://lenovo-pc:9090/plugins/presence/status?";//= "http://lenovo-pc:9090/plugins/presence/status?jid=pacoson@lenovo-pc&type=text&req_jid=tangtang@lenovo-pc";public static final String buildPresenceURL(String from, String to, String type) {return PLUGIN_PRESENT_URL + "jid=" + to + "@" + HOST + "&"+ "req_jid=" + from + "@" + HOST + "&"+ "type=" + type;}
}
package com.xmpp.client;import java.util.Scanner;import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.chat.Chat;// 创建发送msg 线程.
public class MessageHandler {private Chat chat;public MessageHandler(Chat chat) {this.chat = chat;}class Sender implements Runnable{/*public Sender(Chat chat) {MessageHandler.this.chat = chat;}*/public Sender() {}@Overridepublic void run() {Scanner scanner = new Scanner(System.in);while(scanner.hasNext()) {String line = scanner.nextLine();try {chat.sendMessage(line);} catch (NotConnectedException e) {e.printStackTrace();break;}}} }class Receiver {}
}
(干货——只有当 消息接收者处于离线的时候,其接收到的消息才会封装 delay 元素,其属性有 stamp 记录了 msg 发送的时间。(also, you can refer to https://community.igniterealtime.org/thread/22791)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/331037.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java 面试题经典 77 问

转载自 Java 面试题经典 77 问&#xff08;含答案&#xff09;&#xff01;金三银四了&#xff0c;3月底&#xff0c;4月初&#xff0c;找工作换单位的黄金时期。4月初将会有有一大批职场人士流动。。。 作为Java开发码农的你是不是也在蠢蠢欲动&#xff0c;或者已经搞了几轮车…

静态工具类注入service的方法

http://blog.sina.com.cn/s/blog_6e2d53050102wl3x.html

阿里面试回来,想和 Java 程序员谈一谈

转载自 阿里面试回来&#xff0c;想和 Java 程序员谈一谈&#xff01; 第一个问题&#xff1a;阿里面试都问什么&#xff1f; 这个是让LZ最头疼的一个问题&#xff0c;也是群里的猿友们问的最多的一个问题。说实话&#xff0c;LZ只能隐约想起并发、JVM、分布式、TCP/IP协议这…

关于 tomcat启动后无法访问的问题(localhost:8080 (or your port specified))

【0】README1&#xff09;启动 tomcat7&#xff0c; 然后通过 localhost:8080 无法访问&#xff0c;我也是醉了&#xff1b;以下给出了解决方法&#xff1b;【1】解决方法&#xff08;如何让 Server Locations 和 deploye path 成为可编辑区域&#xff09;step1&#xff09;首…

eclipse运行报java.lang.OutOfMemoryError: PermGen space解决方法

分享一个亲测的网址&#xff1a; http://blog.csdn.net/cuker919/article/details/45246073

百度三轮面试回来,想和Java程序员分享一下。

转载自 百度三轮面试回来&#xff0c;想和Java程序员分享一下。一&#xff0c;百度一面1、给一个函数&#xff0c;返回 0 和 1&#xff0c;概率为 p 和 1-p&#xff0c;请你实现一个函数&#xff0c;使得返回 01 概率一样。 2、10 亿个 url&#xff0c;每个 url 大小小于 56B&a…

springmvc sends and receives data by ajax request using json format

【0】README 1) springmvc sends or receives data by ajax request using json format; 【1】 ajax function <script type"text/javascript">var checkoutUserlistIsAccess false;$(document).ready(function(){ $("#first").hide();if(checkout…

在Java中如何设置一个定时任务,在每天的一个时间点自动执行一个特定的程序

Quartz定时机制 首先导入jar包到程序内 quartz-all-1.6.0.jar 然后创建一个XML TimeConfig.xml 名字可以自己定义 <?xml version"1.0" encoding"UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.sp…

程序员如何面对 HR 面试的 40 个问题

转载自 程序员如何面对 HR 面试的 40 个问题&#xff01;讲一个身边朋友亲身经历的故事吧。 一个技术非常牛的朋友去阿里面试&#xff0c;成功通过了几轮技术车轮战&#xff0c;最后躺在了 HR 面上。。。所以&#xff0c;尽管你技术再牛逼&#xff0c;你回答不好 HR 的问题&…

利用ant构建 jsp-servlet-class-jar

【0】README1&#xff09;本文旨在 给出 利用ant构建 jsp->servlet->class->jar 的分析&#xff1b;2&#xff09;本文部分内容转自&#xff1a;http://zfsn.iteye.com/blog/757919【1】ant脚本内容 及其分析1&#xff09;build.xml<?xml version"1.0" …

使用jconsole分析内存情况

http://www.cnblogs.com/dava/p/6686436.html

春节跳槽最新Java面试题

转载自 春节跳槽最新Java面试题及答案整理1.Mybatis与Ibatis的区别 2.Http1与Http2的区别 3.SpringMVC的执行流程 4.JVM内存溢出具体指哪些内存区域&#xff1f;都会抛出什么异常&#xff1f; 5.谈谈对AJAX的理解 6.谈谈对事务的理解 7.String能被继承吗&#xff1f;为什么&…

Tomcat6项目移到Tomcat7 提示 404 解决方案

一个项目在Tomcat6可以运行和正常访问&#xff0c;但是一部署到Tomcat7就提示404错误。那么可以通过以下方法解决&#xff1a; 找到项目下面的 WEB-INF 文件夹 用记事本打开 WEB.XML 找到 <load-on-startup /> 这个标签改为 <load-on-startup >2</load-o…

import openfire4.0.2 source code in eclipse

【0】README1&#xff09;本文旨在给出 导入 openfire4.0.2 源码到 eclipse的具体 steps&#xff1b;2&#xff09;小生我导入该version 的 openfire 用了近2 天时间&#xff0c; 比较心酸&#xff0c;究其原因是 源码 引入的 jar 包不够全面&#xff0c;或引入路径错误&#x…

史上最全Java多线程面试题

转载自 史上最全Java多线程面试题及答案多线程并发编程是Java编程中重要的一块内容&#xff0c;也是面试重点覆盖区域。所以&#xff0c;学好多线程并发编程对Java程序员来来说极其重要的。 下面小编整理了60道最常见的Java多线程面试题及答案&#xff0c;供你学习或者面试参考…

客户端服务端防止用户重复提交表单

一、什么是表单重复提交&#xff1f; 当网络有延迟时&#xff0c;用户提交的表单等数据还没有完成此次提交&#xff0c;但用户又多次点击提交&#xff0c;造成用户数据在数据库或存储中被提交多次。 利用线程延迟&#xff0c;简单模拟重复提交。 表单页面为form.html [html…

405: HTTP method GET is not supported by this URL

【0】README1&#xff09;本文旨在解决 405: HTTP method GET is not supported by this URL 的问题&#xff1b;2&#xff09;本文raw idea is checkouted from http://stackoverflow.com/questions/5370633/405-http-method-get-is-not-supported-by-this-url【1】解决方法…

史上最全Redis面试题

转载自 史上最全Redis面试题及答案。1、什么是Redis&#xff1f; 2、Redis相比memcached有哪些优势&#xff1f; 3、Redis支持哪几种数据类型&#xff1f; 4、Redis主要消耗什么物理资源&#xff1f; 5、Redis的全称是什么&#xff1f; 6、Redis有哪几种数据淘汰策略&#xff1…

多线程的三种实现方法

http://blog.csdn.net/aboy123/article/details/38307539

stomp 连接错误: Whoops! Lost connection to http://localhost:8080/spring13/stomp 的解决方法

【0】README 1&#xff09;本文旨在给出 stomp 连接错误&#xff1a; Whoops! Lost connection to http://localhost:8080/spring13/stomp 的解决方法&#xff1b;you can also refer to this link http://stackoverflow.com/questions/29247956/whoops-lost-connection-to-u…