tigase客户端之smack4.3用法【草稿】

项目介绍
sureim
项目地址:
sureim项目地址
tigase客户端之smack4.3用法【草稿】_第1张图片

git clone https://git.tigase.tech/sureim.git

demo网站:
tigase im

spark 源码编译

获取源代码

git clone https://git.tigase.tech/sureim.git ~/git-projects/sureim

tigase客户端之smack4.3用法【草稿】_第2张图片

配置

spark源代码

spark 项目 git地址

git clone https://github.com/igniterealtime/Spark.git ~/git-projects/spark

tigase客户端之smack4.3用法【草稿】_第3张图片

一个客户端竟然有300mb。。

然后,mvn先编译一下:

$ cd Spark/core
$ mvn exec:java

经过漫长的下载依赖以后就出现这个画面了额。。报错:

tigase客户端之smack4.3用法【草稿】_第4张图片

额,没有一个项目是什么都不用管就能直接运行的。

下面来构建一个idea+gradle的spark源代码项目。

idea项目

smack的项目地址

git地址

下载地址

tigase客户端之smack4.3用法【草稿】_第5张图片

请下载相关jar包然后添加依赖,暂且不表。

代码编写测试

Openfire/XMPP学习之——一个简单的Smack样例

【openfire,smack使用总结】–Smack库的使用

Smack使用简介

编写代码编译:

tigase客户端之smack4.3用法【草稿】_第6张图片

注意,org.jxmpp整个包都是没有的,这里有:
https://mvnrepository.com/artifact/org.jxmpp/jxmpp-core/0.6.3
tigase客户端之smack4.3用法【草稿】_第7张图片

导入gradle然后试试:
tigase客户端之smack4.3用法【草稿】_第8张图片

jid不见,这里有:
https://mvnrepository.com/artifact/org.jxmpp/jxmpp-jid/0.6.3

tigase客户端之smack4.3用法【草稿】_第9张图片

再试试:
tigase客户端之smack4.3用法【草稿】_第10张图片

根据各种错误,至少,gradle中的依赖需要有:

plugins {
    id 'java'
}

group 'net.w2p'
version '1.0-SNAPSHOT'


/***所有项目共通***/
allprojects {
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
    apply plugin: 'java'
    apply plugin: 'idea'
    apply plugin: 'groovy'

    idea {
        module {
            inheritOutputDirs = true
        }
    }
    tasks.withType(JavaCompile) {
        options.encoding = "UTF-8"
    }
    tasks.withType(GroovyCompile) {
        groovyOptions.encoding = "MacRoman"
    }
    repositories {
        maven{
            //更换为阿里的仓库
            url  'http://maven.aliyun.com/nexus/content/groups/public'
        }
        //有些jar包在中央仓库是没有的,需要手动添加上去
//        flatDir {  dirs 'local_jars' }
//        mavenCentral()
    }
}


dependencies {
    compile fileTree(dir:'libs/smack_4_3_1/libs',includes:['*jar'])
    compile 'org.jxmpp:jxmpp-core:0.6.3'
    compile 'org.jxmpp:jxmpp-jid:0.6.3'
    compile 'xmlpull:xmlpull:1.1.3.4a'
    compile 'net.sf.kxml:kxml2:2.3.0'
    compile 'org.minidns:minidns-hla:0.3.3'
    compile 'org.minidns:minidns-core:0.3.3'
//    compile 'org.xbill:dns:2.0.8'
    compile 'dnsjava:dnsjava:2.1.8'
    compile 'org.apache.httpcomponents:httpclient:4.5.6'
    testCompile fileTree(dir:'libs/smack_4_3_1/libs',includes:['*jar'])
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

然后运行:
tigase客户端之smack4.3用法【草稿】_第11张图片

链接不成功,好了,启动自己搭建的tigase server:
tigase客户端之smack4.3用法【草稿】_第12张图片

好了,改改地址端口,然后运行:
tigase客户端之smack4.3用法【草稿】_第13张图片

报错如下:

Exception in thread "main" org.jivesoftware.smack.SmackException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1069)
	at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$300(XMPPTCPConnection.java:993)
	at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:1009)
	at java.lang.Thread.run(Thread.java:748)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
	at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:310)
	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1639)
	at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223)
	at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037)
	at sun.security.ssl.Handshaker.process_record(Handshaker.java:965)
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064)
	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
	at org.jivesoftware.smack.tcp.XMPPTCPConnection.proceedTLSReceived(XMPPTCPConnection.java:803)
	at org.jivesoftware.smack.tcp.XMPPTCPConnection.access$1200(XMPPTCPConnection.java:151)
	at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1064)
	... 3 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:397)
	at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:302)
	at sun.security.validator.Validator.validate(Validator.java:262)
	at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
	at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
	at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1621)
	... 13 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
	at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
	at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:392)
	... 19 more
十二月 19, 2018 4:13:31 下午 org.jivesoftware.smack.AbstractXMPPConnection callConnectionClosedOnErrorListener
警告: Connection XMPPTCPConnection[not-authenticated] (0) closed with error
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
	at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:310)
	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1639)
	at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223)
	at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037)
	at sun.security.ssl.Handshaker.process_record(Handshaker.java:965)
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064)
	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
	at org.jivesoftware.smack.tcp.XMPPTCPConnection.proceedTLSReceived(XMPPTCPConnection.java:803)
	at org.jivesoftware.smack.tcp.XMPPTCPConnection.access$1200(XMPPTCPConnection.java:151)
	at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1064)
	at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$300(XMPPTCPConnection.java:993)
	at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:1009)
	at java.lang.Thread.run(Thread.java:748)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:397)
	at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:302)
	at sun.security.validator.Validator.validate(Validator.java:262)
	at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
	at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
	at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1621)
	... 13 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
	at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
	at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:392)
	... 19 more


Process finished with exit code 1

而服务端有:
tigase客户端之smack4.3用法【草稿】_第14张图片

2018-12-19 16:13:30.784 [ConnectionOpenThread]  SocketThread.()            WARNING:  33 socketReadThreads started.
2018-12-19 16:13:30.802 [ConnectionOpenThread]  SocketThread.()            WARNING:  33 socketWriteThreads started.
2018-12-19 16:13:30.969 [in_23-c2s]        CertificateContainer.createCertificate()  WARNING: Auto-generated certificate for domain: localhost

查找解决方案:

解决Java调用Azure SDK证书错误javax.net.ssl.SSLHandshakeException

HttpsUrlConnection https双向验证

解决 javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path buildin

不对,经过资料核查,发现:
Smack 4 throws “SSLHandshakeException: ValidatorException: SunCertPathBuilderException” on connect

tigase客户端之smack4.3用法【草稿】_第15张图片

资料太久了,不适用于smack4.。。
下面有一些新一点的资料:

smack4中文文档

tigase客户端之smack4.3用法【草稿】_第16张图片

或者直接点:
smack4中文文档

tigase客户端之smack4.3用法【草稿】_第17张图片

也有另一位兄弟也写了:

package main.im_tester;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.roster.Roster;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;

import java.net.InetAddress;

public class FirstTest {

public static void main(String[] args) throws Exception {


    main3();
}

static void main1() throws Exception {
    // Create a connection to the jabber.org server on a specific port.
    XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
            .setUsernameAndPassword("username", "password")
            .setXmppDomain("localhost")
            .setHost("localhost")
            .setPort(5222)
            .build();

// org.xmlpull.v1.

    AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
    conn2.connect().login();
}

static void main2() throws Exception {
    // Create a connection to the jabber.org server.

// AbstractXMPPConnection conn1 = new XMPPTCPConnection(“username”, “password” ,“localhost”);
// conn1.connect();
//
//// Create a connection to the jabber.org server on a specific port.
// XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
// .setUsernameAndPassword(“username”, “password”)
// .setServiceName(“localhost”)
// .setHost(“localhost”)
// .setPort(5222)
// .build();
//
// AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
// conn2.connect();

    // Create the configuration for this new connection
    XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();

// configBuilder.setUsernameAndPassword(“username”, “password”);
configBuilder.setResource(“SomeResource”);
configBuilder.setXmppDomain(“localhost”);
//–这个比较重要,假如不设置的话是默认开启加密传输的,到时候会有错误:javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path buildin
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);

    AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());

// Connect to the server
connection.connect();
// Log into the server
// connection.login();
// Disconnect from the server
connection.disconnect();
}

public static void main3(){

    XMPPConnection connection=createConnection();
    ((XMPPTCPConnection) connection).disconnect();
}

public static XMPPTCPConnection createConnection() {
    XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
    XMPPTCPConnection connection=null;
    try {
        //设置openfire主机IP
        config.setHostAddress(InetAddress.getByName("localhost"));
        //设置openfire服务器名称
        config.setXmppDomain("localhost");
        //设置端口号:默认5222
        config.setPort(5222);
        //禁用SSL连接
        config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled).setCompressionEnabled(false);

// config.setDebuggerEnabled(true);
//设置离线状态
config.setSendPresence(false);
//需要经过同意才可以添加好友
Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);

// config.setUsernameAndPassword(“t1”,“t2”);
connection = new XMPPTCPConnection(config.build());
connection.connect();
// connection.login();

        System.out.println("成功链接上tigase 服务器");

    } catch (Exception e) {

// Logger.d(“openfire连接失败,请检查是否开启服务器!”);
e.printStackTrace();
}
return connection;
}

}
XMPP系列之Smack(4.1.3)(一)登录服务器

这一位兄弟也是:
Smack4.20实现连接登陆(1)

tigase客户端之smack4.3用法【草稿】_第18张图片

好了,参考上面的来写代码:

package main.im_tester;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.roster.Roster;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;

import java.net.InetAddress;

public class FirstTest {

    public static void main(String[] args) throws Exception {


        main3();
    }

    static void main1() throws Exception {
        // Create a connection to the jabber.org server on a specific port.
        XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                .setUsernameAndPassword("username", "password")
                .setXmppDomain("localhost")
                .setHost("localhost")
                .setPort(5222)
                .build();
//        org.xmlpull.v1.


        AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
        conn2.connect().login();
    }

    static void main2() throws Exception {
        // Create a connection to the jabber.org server.
//        AbstractXMPPConnection conn1 = new XMPPTCPConnection("username", "password" ,"localhost");
//        conn1.connect();
//
//// Create a connection to the jabber.org server on a specific port.
//        XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
//                .setUsernameAndPassword("username", "password")
//                .setServiceName("localhost")
//                .setHost("localhost")
//                .setPort(5222)
//                .build();
//
//        AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
//        conn2.connect();

        // Create the configuration for this new connection
        XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
//        configBuilder.setUsernameAndPassword("username", "password");
        configBuilder.setResource("SomeResource");
        configBuilder.setXmppDomain("localhost");
        //--这个比较重要,假如不设置的话是默认开启加密传输的,到时候会有错误:javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path buildin
        configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);

        AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
// Connect to the server
        connection.connect();
// Log into the server
//        connection.login();
// Disconnect from the server
        connection.disconnect();
    }

    public static void main3(){

        XMPPConnection connection=createConnection();
        ((XMPPTCPConnection) connection).disconnect();
    }

    public static XMPPTCPConnection createConnection() {
        XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
        XMPPTCPConnection connection=null;
        try {
            //设置openfire主机IP
            config.setHostAddress(InetAddress.getByName("localhost"));
            //设置openfire服务器名称
            config.setXmppDomain("localhost");
            //设置端口号:默认5222
            config.setPort(5222);
            //禁用SSL连接
            config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled).setCompressionEnabled(false);

//            config.setDebuggerEnabled(true);
            //设置离线状态
            config.setSendPresence(false);
            //需要经过同意才可以添加好友
            Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);


//            config.setUsernameAndPassword("t1","t2");
            connection = new XMPPTCPConnection(config.build());
            connection.connect();
//            connection.login();

            System.out.println("成功链接上tigase 服务器");

        } catch (Exception e) {
//            Logger.d("openfire连接失败,请检查是否开启服务器!");
            e.printStackTrace();
        }
        return connection;
    }

}

测试:
tigase客户端之smack4.3用法【草稿】_第19张图片

终于可以连接上了。

顺便,gradle也变更一下:

plugins {
    id 'java'
}

group 'net.w2p'
version '1.0-SNAPSHOT'


/***所有项目共通***/
allprojects {
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
    apply plugin: 'java'
    apply plugin: 'idea'
    apply plugin: 'groovy'

    idea {
        module {
            inheritOutputDirs = true
        }
    }
    tasks.withType(JavaCompile) {
        options.encoding = "UTF-8"
    }
    tasks.withType(GroovyCompile) {
        groovyOptions.encoding = "MacRoman"
    }
    repositories {
        maven{
            //更换为阿里的仓库
            url  'http://maven.aliyun.com/nexus/content/groups/public'
        }
        //有些jar包在中央仓库是没有的,需要手动添加上去
//        flatDir {  dirs 'local_jars' }
//        mavenCentral()
    }
}


dependencies {
    /*
    --- 注意,这里不要直接下载jar来依赖了。用gradle上面的依赖。
    compile fileTree(dir:'libs/smack_4_3_1/libs',includes:['*jar'])
    compile 'org.jxmpp:jxmpp-core:0.6.3'
    compile 'org.jxmpp:jxmpp-jid:0.6.3'
    compile 'xmlpull:xmlpull:1.1.3.4a'
    compile 'net.sf.kxml:kxml2:2.3.0'
    compile 'org.minidns:minidns-hla:0.3.3'
    compile 'org.minidns:minidns-core:0.3.3'
//    compile 'org.xbill:dns:2.0.8'
    compile 'dnsjava:dnsjava:2.1.8'
    compile 'org.apache.httpcomponents:httpclient:4.5.6'
    testCompile fileTree(dir:'libs/smack_4_3_1/libs',includes:['*jar'])
    */
    testCompile group: 'junit', name: 'junit', version: '4.12'


    compile "org.igniterealtime.smack:smack-core:4.3.1"
    compile "org.igniterealtime.smack:smack-tcp:4.3.1"
    compile "org.igniterealtime.smack:smack-im:4.3.1"
}

账号注册

Smack 4.1.9(一)初始化、注册、登录、登出、注销

好了,这一节来看看怎么注册:

参考代码有:


    final String newUsername = newRandomUUID();  
    final String newPassword = newRandomUUID();  
    Registration registration = new Registration();  
      
    PacketFilter packetFilter = new AndFilter(new PacketIDFilter(  
            registration.getPacketID()), new PacketTypeFilter(  
            IQ.class));  
    PacketListener packetListener = new PacketListener() {  
        @Override  
        public void processPacket(Packet packet) {  
            // 服务器回复客户端  
            if(packet instanceof IQ) {  
                IQ response = (IQ) packet;  
                if(response.getType() == IQ.Type.ERROR) { // 注册失败  
                    if (!response.getError().toString().contains(  
                            "409")) {  
                        Log.e(LOGTAG,"Unknown error while registering XMPP account! " + response.getError().getCondition());  
                    }  
                } else if(response.getType() == IQ.Type.RESULT) { // 注册成功  
                    mXmppManager.setUsername(newUsername);  
                    mXmppManager.setPassword(newPassword);  
                    // 把用户名和密码都保存到磁盘  
                    Editor editor = mSharedPrefs.edit();  
                    editor.putString(Contants.XMPP_USERNAME, newUsername);  
                    editor.putString(Contants.XMPP_PASSWORD, newPassword);  
                    editor.commit();  
                      
                    mXmppManager.runTask();  
                }  
            }  
        }  
    };  
    // 给注册的Packet设置Listener,因为只有等到正真注册成功后,我们才可以交流  
    mConnection.addPacketListener(packetListener, packetFilter);  
      
    registration.setType(IQ.Type.SET);  
    registration.addAttribute("username", newUsername);  
    registration.addAttribute("password", newPassword);  
      
    // 向服务器端,发送注册Packet包,注意其中Registration是Packet的子类  
    mConnection.sendPacket(registration);  

https://blog.csdn.net/sinat_25957705/article/details/67654828

还有:

// 注册关键代码

        Map map = new HashMap<>();
        map.put("account",account);
        map.put("password",password);
        map.put("android","");

        Registration mRegistration = new Registration(map);
        mRegistration.setType(IQ.Type.set);
        mRegistration.setTo(this.mConnection.getServiceName());

        try {
            this.mConnection.sendStanza(mRegistration);

            StanzaFilter filter = new AndFilter(new StanzaIdFilter(mRegistration.getStanzaId()), new StanzaTypeFilter(IQ.class));
            PacketCollector collector = mConnection.createPacketCollector(filter);

            IQ result = (IQ) collector.nextResult(mConnection.getPacketReplyTimeout());
            collector.cancel();
            if (result == null || result.getType() == IQ.Type.error) {
                // register error
            } else {
                // register suceess!
            }

        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }

作者:DevSiven
链接:https://www.jianshu.com/p/9c0c3ed181aa
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

不过。。。这些都运行不通。。。不解啊。。

直到看到下面的:

SMACK 4.1 Account manager: Private Access Error in account registration

tigase客户端之smack4.3用法【草稿】_第20张图片

tigase客户端之smack4.3用法【草稿】_第21张图片

tigase客户端之smack4.3用法【草稿】_第22张图片

还有这一篇:

XMPP register new user

tigase客户端之smack4.3用法【草稿】_第23张图片

tigase客户端之smack4.3用法【草稿】_第24张图片

tigase客户端之smack4.3用法【草稿】_第25张图片

这样才比较明了:
于是代码如下:

今天遇到了这种问题:

tigase客户端之smack4.3用法【草稿】_第26张图片

根据查询,是缺少包了:

https://bbs.csdn.net/topics/391043545

tigase客户端之smack4.3用法【草稿】_第27张图片

gradle添加依赖,然后:

tigase客户端之smack4.3用法【草稿】_第28张图片

ok。

注册的代码是:

 private void testReg2(){
        XMPPTCPConnection conn=getXmppConnection();

//        AccountManager am = new AccountManager(conn);
        AccountManager am = AccountManager.getInstance(conn);
        Map mp = new HashMap();
        // adding or set elements in Map by put method key and value
        // pair
        mp.put("username", "user3");
        mp.put("password", "ps3");
        mp.put("name", "user3");
        mp.put("email", "[email protected]");

        try {
            if(!am.supportsAccountCreation()){
                System.out.println("当前链接不支持创建账号!!!!");
                return;
            }

            am.createAccount(Localpart.from("user3"), "ps3");
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
        catch (Exception ed){
            ed.printStackTrace();
        }
        finally {
            conn.disconnect();
        }


    }

执行结果:

tigase客户端之smack4.3用法【草稿】_第29张图片

需要认证吗。。。
嗯。。。
加一个允许不安全创建:

am.sensitiveOperationOverInsecureConnection(true);

好了,即代码如下:
我已经成功创建了一个了,现在账号密码要换一换:

private void testReg2(){
        XMPPTCPConnection conn=getXmppConnection();

//        AccountManager am = new AccountManager(conn);
        AccountManager am = AccountManager.getInstance(conn);
        am.sensitiveOperationOverInsecureConnection(true);
        Map mp = new HashMap();
        // adding or set elements in Map by put method key and value
        // pair
        mp.put("username", "test001");
        mp.put("password", "123456");
        mp.put("name", "吴日天");
        mp.put("email", "日天@日天.com");

        try {
            if(!am.supportsAccountCreation()){
                System.out.println("当前链接不支持创建账号!!!!");
                return;
            }

            am.createAccount(Localpart.from("test001"), "123456",mp);
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
        catch (Exception ed){
            ed.printStackTrace();
        }
        finally {
            conn.disconnect();
        }


    }

tigase客户端之smack4.3用法【草稿】_第30张图片

下面看看数据库里面的账号数据:
tigase客户端之smack4.3用法【草稿】_第31张图片

注册成功。

smack账号登录

用我们刚才创建的账号登录:

    @Test

    public void testLogin(){
        login();
    }
    public void  login() {
        XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
        XMPPTCPConnection connection=null;
        try {
            //设置openfire主机IP
            config.setHostAddress(InetAddress.getByName("localhost"));
            //设置openfire服务器名称
            config.setXmppDomain("localhost");
            //设置端口号:默认5222
            config.setPort(5222);
            //禁用SSL连接
            config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled).setCompressionEnabled(false);

//            config.setDebuggerEnabled(true);
            //设置离线状态
            config.setSendPresence(false);
            //需要经过同意才可以添加好友
            Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);

            config.setUsernameAndPassword("test001","123456");



//            config.setUsernameAndPassword("t1","t2");
            connection = new XMPPTCPConnection(config.build());
            connection.connect();
            connection.login();

            System.out.println("成功链接上tigase 服务器");
            System.out.println("成功登录");

        } catch (Exception e) {
//            Logger.d("openfire连接失败,请检查是否开启服务器!");
            System.out.println("登录失败");
            e.printStackTrace();
        }
        finally {
            if(connection!=null){
                connection.disconnect();
            }
        }
    }

运行结果

tigase客户端之smack4.3用法【草稿】_第32张图片

你可能感兴趣的:(即时通讯)