smack android集成问题记录

来源:互联网 发布:手机cpu控制软件 编辑:程序博客网 时间:2024/06/08 15:24

最近使用的项目中需要集成即时通讯,故使用smack 4.1.0 作为集成,集成方法见

https://github.com/igniterealtime/Smack/wiki/Smack-4.1-Readme-and-Upgrade-Guide

由于并不懂的新xmpp协议,所有先写个Demo来测试一下功能,有一些坑,特此记录一下:

1.连接

Thread connectThread = new Thread(){    @Override    public void run() {        //配置连接        XMPPTCPConnectionConfiguration mConnectConfig = XMPPTCPConnectionConfiguration.builder()                .setServiceName(HOST).setUsernameAndPassword("18101399687@"+HOST,"123456").setDebuggerEnabled(true).setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)                .setCompressionEnabled(false).build();        //配置授权信息        SASLMechanism mechanism = new SASLDigestMD5Mechanism();        SASLAuthentication.registerSASLMechanism(mechanism);        SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");        SASLAuthentication.unBlacklistSASLMechanism("DIGEST-MD5");        // Create a connection to the igniterealtime.org XMPP server.        con = new XMPPTCPConnection(mConnectConfig);        try {            con.connect();        } catch (SmackException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } catch (XMPPException e) {            e.printStackTrace();        }    }};connectThread.start();
其中setServiceName设置的是服务器地址,UserName 需要使用JID全名,由UserName@Host组成。

其次为了顺利登陆需要配置开启SASL机制,否则登陆时会报错org.jivesoftware.smack.sasl.SASLErrorException: SASLError using PLAIN: not-authorized

2.登陆

try {    con.login();} catch (XMPPException e) {    e.printStackTrace();} catch (SmackException e) {    e.printStackTrace();} catch (IOException e) {    e.printStackTrace();}
3.发送文字消息

Chat chat = ChatManager.getInstanceFor(con).createChat("18101399690@27.17.34.22",this);try {    chat.sendMessage("Hello world!");} catch (SmackException.NotConnectedException e) {    e.printStackTrace();}
4.接收消息

ChatMessageListener
就可以了

0 0
原创粉丝点击