XMPP 学习笔记五 Strophe API学习

文档:
http://strophe.im/strophejs/doc/1.2.6/files/strophe-js.html

1. 与服务器建立连接

// XMPP服务器BOSH地址
var BOSH_SERVICE = 'http://pc-20160820rwic:7070/http-bind/';

// XMPP连接
var connection = null;

// 当前状态是否连接
var connected = false;

// 连接状态改变的事件
function onConnect(status) {
    console.log(status)
    if (status == Strophe.Status.CONNFAIL) {
        console.log("连接失败!");
    } else if (status == Strophe.Status.AUTHFAIL) {
        console.log("登录失败!");
    } else if (status == Strophe.Status.DISCONNECTED) {
        console.log("连接断开!");
        connected = false;
    } else if (status == Strophe.Status.CONNECTED) {
        console.log("连接成功,可以开始聊天了!");
        connected = true;

        // 当接收到节,调用onMessage回调函数
        connection.addHandler(onMessage, null, 'message', null, null, null);

        // 首先要发送一个给服务器(initial presence)
        connection.send($pres().tree());
    }
}
///建立连接
if(!connected) {
    connection = new Strophe.Connection(BOSH_SERVICE);
    connection.connect(jid, password, onConnect);
}

2. 发送消息

// 创建一个元素并发送
var msg = $msg({
    to: toJid, 
    from: fromJid, 
    type: 'chat'
}).c("body", null, 要发送的内容);
connection.send(msg.tree());

3. 接收消息

// 接收到
function onMessage(msg) {
    // 解析出的from、type属性,以及body子元素
    var from = msg.getAttribute('from');
    var type = msg.getAttribute('type');
    var elems = msg.getElementsByTagName('body');

    if (type == "chat" && elems.length > 0) {
        var body = elems[0];
        console.log(from , Strophe.getText(body) );
    }
    return true;
}

注意事项:
发送者与接收者JID要填写完整的地址,如:
test1@pc-20160820rwic

4. 获得好友列表

    var iq = $iq({type: 'get'}).c('query', {xmlns: 'jabber:iq:roster'});
    connection.sendIQ(iq, function(a){
        console.log('sent iq',a);

        $(a).find('item').each(function(){
            var jid = $(this).attr('jid'); // jid
            console.log('jid',jid);
        });     
    });

你可能感兴趣的:(JAVA-XMPP)