tigase客户端之smack用法【草稿】

项目介绍
sureim
项目地址:
sureim项目地址
在这里插入图片描述

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

demo网站:
tigase im

spark 源码编译

获取源代码

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

在这里插入图片描述

配置

spark源代码

spark 项目 git地址

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

在这里插入图片描述

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

然后,mvn先编译一下:

$ cd Spark/core
$ mvn exec:java

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

在这里插入图片描述

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

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

idea项目

smack的项目地址

git地址

下载地址

在这里插入图片描述

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

代码编写测试

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

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

Smack使用简介

编写代码编译:

在这里插入图片描述

注意,org.jxmpp整个包都是没有的,这里有:
https://mvnrepository.com/artifact/org.jxmpp/jxmpp-core/0.6.3
在这里插入图片描述

导入gradle然后试试:
在这里插入图片描述

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

在这里插入图片描述

再试试:
在这里插入图片描述

根据各种错误,至少,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 server:
在这里插入图片描述

好了,改改地址端口,然后运行:
在这里插入图片描述

报错如下:

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

而服务端有:
在这里插入图片描述

2018-12-19 16:13:30.784 [ConnectionOpenThread]  SocketThread.<clinit>()            WARNING:  33 socketReadThreads started.
2018-12-19 16:13:30.802 [ConnectionOpenThread]  SocketThread.<clinit>()            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

在这里插入图片描述

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

smack4中文文档

在这里插入图片描述

或者直接点:
smack4中文文档

在这里插入图片描述

也有另一位兄弟也写了:

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)

在这里插入图片描述

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

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;
    }

}

测试:
在这里插入图片描述

终于可以连接上了。

顺便,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"
}

猜你喜欢

转载自blog.csdn.net/cdnight/article/details/85072283