XMPP客戶端開發(1)--鏈接和登陸

Smack可用於XMPP客戶端的開發,下載Smack,將相關jar文件導入後,便可以開始XMPP客戶端的開發。服務器

如下代碼實現了客戶端鏈接Tigase服務器,並根據用戶名和密碼登陸。spa

package Xmpp;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;

/**
 * XMPP Client
 * @author    HZ
 * @since    2014-09-01
 * @version    1.0.0
 */
public class Client {
    
    public static XMPPConnection xmpp_conn;
    public static ConnectionConfiguration xmpp_conf;
    
    // 服務器IP
    public static String xmpp_ip = new String("10.3.93.213");
    // 服務器名
    public static String xmpp_host = new String("tsung213");
    // 服務器端口
    public static int xmpp_port = 5222;
    
    // 用戶名和密碼
    public static String user = new String("hz_12");
    public static String pass = new String("123456");

    public static void main(String[] args) {        
        conn();
    }
    
    // 鏈接服務器
    public static void conn(){
        
        try{
            // 配置鏈接 
            xmpp_conf = new ConnectionConfiguration(xmpp_ip, xmpp_port, xmpp_host);
            xmpp_conf.setReconnectionAllowed(true);      
            xmpp_conf.setSecurityMode(SecurityMode.disabled);       
            xmpp_conf.setSASLAuthenticationEnabled(false);
            xmpp_conf.setCompressionEnabled(false);
        
            // 鏈接,並根據用戶名和密碼登陸
            xmpp_conn = new XMPPConnection(xmpp_conf);
            xmpp_conn.DEBUG_ENABLED = true;
            xmpp_conn.connect();
            xmpp_conn.login(user, pass);
            
            // 獲取相關變量
            String tmp;
            tmp = xmpp_conn.getConnectionID();
            System.out.println("ConnectionID:" + tmp);
            tmp = xmpp_conn.getHost();
            System.out.println("Host:" + tmp);
            tmp = xmpp_conn.getServiceName();
            System.out.println("ServiceName:" + tmp);
            tmp = xmpp_conn.getUser();
            System.out.println("User:" + tmp);
        }
        catch (XMPPException e){
            System.out.println("Error:" + e.toString());
        }
        
    }

}

運行結果:3d

相關文章
相關標籤/搜索