安卓大做业要作一个聊天室,而后查到了XMPP协议,而后搭建了openfire服务器(就是安装一下便可)
但是到了XMPP编程的时候发现了问题,Smack是一个开源的已于使用的XMPP客户端类库,我选择这个类库,不过网上的资料不少版本过老,就本身去github查了查。这也是开源好处。
首先,要把Smack导入到Android Studio,
发现Smack不须要下载,能够在AS配置便可,html
首先是Smack的文档:https://download.igniterealtime.org/smack/docs/latest/javadoc/
编程的时候参照上面就行。java
在app文件夹下的build.gradle放入以下android
With Gradle repositories { maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } mavenCentral() }
在文件中的dependencies范围下加入下面字段git
compile "org.igniterealtime.smack:smack-android-extensions:4.3.0" compile "org.igniterealtime.smack:smack-tcp:4.3.0"
而后Sync now就会自动下载Smackgithub
主要依据:https://download.igniterealtime.org/smack/docs/latest/documentation.htmlweb
首先注意openfire服务器中加入一个用户,好比我加入的ace,密码ace
下面这幅图是XMPP地址格式 用户名@域/资源,通常不用到资源
编程
// 创建链接配置 XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder(); //设置用户名密码 configBuilder.setUsernameAndPassword("ace", "ace"); //设置XMPP域名,也就是XMPP协议后的@后的东西(在实际操做的时候发现参数写什么均可以正常运行,可是不能没有这句话,个人代码中,参数是localhost configBuilder.setXmppDomain("jabber.org"); //设置主机位置,也就是服务器ip configBuilder.setHostAddress(InetAddress.getByName("xxx.xxx.xxx.xxx")); //等同于上面那句话builder.setHost("xxx.xxx.xxx.xxx"); //设置端口号,默认5222 configBuilder.setPort(5222); //设置不验证,不然须要TLS验证 configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled); //设置能够更改用户当前状态(在线、离线等等) configBuilder.setSendPresence(true); //设置在线 Presence presence = new Presence(Presence.Type.available); //通知在线 xmpptcpConnection.sendStanza(presence); //经过配置创建链接 AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build()); // 链接到服务器 connection.connect(); // Log into the server connection.login(); ... // 断开链接 connection.disconnect();
下面是用户状态全部取值
服务器
// 假设咱们已经建立了链接connection 获取connection回话管理器实例 ChatManager chatManager = ChatManager.getInstanceFor(connection); //添加监听器 chatManager.addIncomingListener(new IncomingChatMessageListener() { @Override void newIncomingMessage(EntityBareJid from, Message message, Chat chat) { System.out.println("New message from " + from + ": " + message.getBody()); } });
// 假设咱们已经建立了链接connection 获取connection回话管理器实例 ChatManager chatManager = ChatManager.getInstanceFor(connection); //这里就是Xmpp地址,用户名@域名,能够在openfire中查询 EntityBareJid jid = JidCreate.entityBareFrom("ace@localhost"); Chat chat = chatManager.chatWith(jid); chat.send("Howdy!");
plus:若是想要附加信息,使用app
Message newMessage = new Message(); newMessage.setBody("Howdy!"); // 添加附加信息 JivePropertiesManager.addProperty(newMessage, "favoriteColor", "red"); chat.send(newMessage);
接着就大功告成了~maven