Xmpp學(xué)習(xí)之Android-smack入門指導(dǎo)

版權(quán)聲明:本文為博主原創(chuàng)文章,未經(jīng)博主允許不得轉(zhuǎn)載。

轉(zhuǎn)載請表明出處:http://www.itdecent.cn/p/049ef7d049eb

[TOC]
WTF簡書不支持 toc 目錄模式,簡單截圖一張。


img-w140
img-w140

在此為后面的smack學(xué)習(xí)做筆記,以作備忘。
以下是本次采用的Demo環(huán)境:

  • Openfire 4.3.8.2
  • smack4.2.1

smack之登錄

xmpp首次登錄,可以通過自定義的Socket去進(jìn)行連接服務(wù)器,如果你服務(wù)器不是配置了非常特殊TLS連接,一般可以是用Smack中的XMPPConnection類建立連接(我推薦通過API中的XMPPConnection去連接,能省去很多復(fù)雜的過程),下面我講一下XMPPConnection的連接配置。

基礎(chǔ)配置

XMPPConnection的連接需要通過XMPPTCPConnectionConfiguration.builder()配置你在Openfire設(shè)置的配置,代碼如下:

XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setXmppDomain("server domain");
builder.setHostAddress(InetAddress.getByName("you host address"));
//default port 5222
builder.setPort(you port);
builder.setDebuggerEnabled(true);
builder.setCompressionEnabled(true);
builder.setSendPresence(false);
builder.setUsernameAndPassword("username", "password");

像如上代碼中的,XmppDomain是必須配置(這里的```XmppDomain```會拼接在首次建立```Socket```的IQ中的to和from中),HostAddress是你運(yùn)行服務(wù)器的域名或IP地址,Port是你登錄的端口,在Openfire中默認(rèn)是5222端口,但如果你的服務(wù)器使用的是Nginx做前置機(jī),那么這里你需要填入你的Nginx配置的端口。  

### 進(jìn)階配置
可能看到這里,你會覺得很奇怪,為什么還有個(gè)進(jìn)階配置,難道Openfire難道登錄就是一個(gè)普通的Socket登錄嗎?這樣很容易被黑吧,沒錯(cuò),實(shí)際上還有進(jìn)階配置滿足加密連接和自定義的要求,如TLS登錄或SSL登錄或者壓縮通訊,如下例子: 

* 如自定義的TLS登錄  
TLS的登錄方式,具體筆者也沒實(shí)踐過,歡迎拍磚。

```Java
SSLContext sslContext = SSLContext.getInstance("TLS");

MemorizingTrustManager mtm = new MemorizingTrustManager(getApplicationContext());

MemorizingKeyManager memorizingKeyManager = new MemorizingKeyManager(getApplicationContext(), "123456");

sslContext.init(new X509KeyManager[]{(X509KeyManager) memorizingKeyManager}
   , new X509TrustManager[]{mtm}, new java.security.SecureRandom());
   
builder.setCustomSSLContext(sslContext);

builder.setHostnameVerifier(mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier())); 

以上的代碼需要注意一點(diǎn)是內(nèi)中的MemorizingTrustManager,他來自于MemorizingTrustManager,而另外一個(gè)MemorizingKeyManager是自定義的類,內(nèi)中的代碼其實(shí)就是自定義了一個(gè)繼承自X509TrustManager的類,這里不做深究,如有需要可以聯(lián)系我。

  • 使用舊的TLS連接
    實(shí)際上這里的意思是關(guān)閉安全模式,可以通過如下代碼關(guān)閉安全模式
* 其他的兼容方式  
    實(shí)際上就是沿用上面的那個(gè)函數(shù)```builder.setSecurityMode```中填入的另外兩種方式,以下是這三種方式的注釋和描述:
    
```JavaDoc
/**
 * Security via TLS encryption is required in order to connect. If the server
 * does not offer TLS or if the TLS negotiation fails, the connection to the server
 * will fail.
 */
required,

/**
 * Security via TLS encryption is used whenever it's available. This is the
 * default setting.
 * <p>
 * <b>Do not use this setting</b> unless you can't use {@link #required}. An attacker could easily perform a
 * Man-in-the-middle attack and prevent TLS from being used, leaving you with an unencrypted (and
 * unauthenticated) connection.
 * </p>
 */
ifpossible,

/**
 * Security via TLS encryption is disabled and only un-encrypted connections will
 * be used. If only TLS encryption is available from the server, the connection
 * will fail.
 */
disabled
  • 開啟通訊壓縮
    這里的通訊壓縮開啟后,傳輸?shù)牧髁繉⒐?jié)省90%
builder.setCompressionEnabled(true);
  • SASL認(rèn)證
    Openfire服務(wù)器默認(rèn)支持 PLAIN 、ANONYMOUS 、JIVE-SHAREDSECRET,這里我的服務(wù)器開啟的是 PLAIN ,所以我使用 PLAIN
SASLAuthentication.blacklistSASLMechanism(SASLPlainMechanism.NAME);

登錄服務(wù)器

通過了上面的配置后,咱們可以登錄Openfire系統(tǒng)了,相當(dāng)簡單:

AbstractXMPPConnection xmpptcpConnection = new XMPPTCPConnection(builder.build());
if (!xmpptcpConnection.isConnected()) {
    xmpptcpConnection.connect();
}else{
    System.out.println("Already connected");
}

如果以上的配置和服務(wù)器的自定義不匹配,在建立連接的這一步會拋出異常,具體的異常可以通過對應(yīng)方案處理,這里不詳談。

登錄底層報(bào)文通訊簡要解析

作為程序猿,難道會使用API夠了嗎?不,我們繼續(xù)折騰,下面一起來看一下底層的通訊報(bào)文流程。

  • 在建立了Socket后,client會向服務(wù)器發(fā)出一條xml
SENT
<stream:stream 
    xmlns='jabber:client'   
    to='server domain' 
    xmlns:stream='http://etherx.jabber.org/streams' 
    version='1.0' 
    from='username@server domain' 
    xml:lang='en'>
  • 服務(wù)器解析到上面的指令后,會返回用于告訴client可選的SASL方式
RECV
<?xml version='1.0' encoding='UTF-8'?>
    <stream:stream xmlns:stream="http://etherx.jabber.org/streams"  
    xmlns="jabber:client" 
    from="im" 
    id="c997c3a8" 
    xml:lang="en" 
    version="1.0">
        <stream:features>
        <starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls">
        </starttls>
        <mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
            <mechanism>PLAIN</mechanism>
            <mechanism>ANONYMOUS</mechanism>
            <mechanism>JIVE-SHAREDSECRET</mechanism>
        </mechanisms>
        <compression xmlns="http://jabber.org/features/compress">
            <method>zlib</method>
        </compression>
        <auth xmlns="http://jabber.org/features/iq-auth"/>
        <register xmlns="http://jabber.org/features/iq-register"/>
    </stream:features>
  • 客戶端選擇ANONYMOUS認(rèn)證方式
SENT
<auth 
    xmlns='urn:ietf:params:xml:ns:xmpp-sasl'    
    mechanism='ANONYMOUS'>=</auth>
  • 服務(wù)器通過計(jì)算加密后的密碼后,服務(wù)器將返回
RECV
<success xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>
  • 當(dāng)客戶端收到以上命令后,將首次發(fā)起連接的id發(fā)送到服務(wù)器
SENT
<stream:stream 
    xmlns='jabber:client' 
    to='server domain' 
    xmlns:stream='http://etherx.jabber.org/streams' 
    version='1.0'
    from='username@server domain' 
    id='c997c3a8' 
    xml:lang='en'>
  • 這時(shí)服務(wù)器會返回如下內(nèi)容說明此時(shí)的已經(jīng)成功綁定了當(dāng)前的Socket,
RECV
<?xml version='1.0' encoding='UTF-8'?>
    <stream:stream 
        xmlns:stream="http://etherx.jabber.org/streams" 
        xmlns="jabber:client" 
        from="im" 
        id="c997c3a8" 
        xml:lang="en"
        version="1.0">
            <stream:features>
                <compression 
                    xmlns="http://jabber.org/features/compress">
                    <method>zlib</method>
                </compression>
                <bind 
                    xmlns="urn:ietf:params:xml:ns:xmpp-bind"/>
                    <session 
                        xmlns="urn:ietf:params:xml:ns:xmpp-session"/>
    </stream:features>
  • 客戶端在接收到如上的內(nèi)容后會告訴服務(wù)器開啟壓縮
SENT
<compress xmlns='http://jabber.org/protocol/compress'><method>zlib</method></compress>
  • 服務(wù)器返回
RECV
<compressed xmlns='http://jabber.org/protocol/compress'/>
  • 客戶端收到服務(wù)器的響應(yīng)命令后,重新建立一個(gè)Socket,發(fā)送指令
SENT
<stream:stream 
    xmlns='jabber:client'       
    to='server domain' 
    xmlns:stream='http://etherx.jabber.org/streams' 
    version='1.0' 
    from='username@server domain'  
    id='c997c3a8' 
    xml:lang='en'>
  • 服務(wù)器將返回,不知道你有沒有發(fā)現(xiàn),這里的id="c997c3a8"還是那個(gè)id
RECV
<?xml version='1.0' encoding='UTF-8'?>
    <stream:stream 
        xmlns:stream="http://etherx.jabber.org/streams" 
        xmlns="jabber:client" 
        from="im" 
        id="c997c3a8" 
        xml:lang="en" 
        version="1.0">
        <stream:features>
            <mechanisms 
            xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
                <mechanism>PLAIN</mechanism>
                <mechanism>ANONYMOUS</mechanism>
                <mechanism>JIVE-SHAREDSECRET</mechanism>
            </mechanisms>
            <bind 
                xmlns="urn:ietf:params:xml:ns:xmpp-bind"/>
                <session 
                    xmlns="urn:ietf:params:xml:ns:xmpp-session"/>
    </stream:features>
  • 實(shí)際上到這里客戶端的登錄已經(jīng)完成了,但是還沒算成功,接下來可以開始做綁定Socket的操作了
SENT
<iq 
    id='b86j8-4' 
    type='set'>
        <bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'>
        </bind>
</iq>
  • 服務(wù)器返回綁定了JID = c997c3a8的客戶端
RECV
<iq 
    type="result" 
    id="b86j8-4" 
    to="im/c997c3a8">
    <bind 
            xmlns="urn:ietf:params:xml:ns:xmpp-bind">
        <jid>c997c3a8@im/c997c3a8</jid>
    </bind>
</iq>
  • 客戶端繼續(xù)請求,開啟一個(gè)session
SENT
<iq id='b86j8-6' type='set'><session xmlns='urn:ietf:params:xml:ns:xmpp-session'/></iq>
  • 這時(shí)服務(wù)器返回
RECV
<iq 
    type="result" 
    id="b86j8-6" 
    to="c997c3a8@im/c997c3a8"/>
  • 到此,整個(gè)登錄流程已經(jīng)成功了,接下來可以做一些用戶信息的獲取等操作。

結(jié)尾

本篇帶領(lǐng)大家了解如何利用smack登錄Openfire和XMPP的報(bào)文流程,下一個(gè)章節(jié)將會帶大家進(jìn)入xmpp的里面,看看獲取用戶信息等具體的操作。

引用

https://download.igniterealtime.org/smack/docs/latest/documentation/gettingstarted.html/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,545評論 19 139
  • https://nodejs.org/api/documentation.html 工具模塊 Assert 測試 ...
    KeKeMars閱讀 6,603評論 0 6
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,001評論 25 709
  • 關(guān)于XMPP最權(quán)威的講解:http://www.jabbercn.org/RFC3920(這個(gè)才是最權(quán)威的,下面文...
    隨風(fēng)飄蕩的小逗逼閱讀 1,640評論 1 5
  • 引言 開發(fā)這個(gè)插件的目的是因?yàn)樽罱麭oss一再強(qiáng)調(diào)紀(jì)律,不允許使用QQ,不過作為十幾年Q齡的老用戶,早已經(jīng)習(xí)慣了Q...
    Jamling閱讀 683評論 0 1

友情鏈接更多精彩內(nèi)容