XMPP 学习笔记四 Strophe API学习

    xiaoxiao2021-11-19  58

    转自:http://blog.csdn.net/xundh/article/details/52419694

    文档:  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; // 当接收到<message>节,调用onMessage回调函数 connection.addHandler(onMessage, null, 'message', null, null, null); // 首先要发送一个<presence>给服务器(initial presence) connection.send($pres().tree()); } } ///建立连接 if(!connected) { connection = new Strophe.Connection(BOSH_SERVICE); connection.connect(jid, password, onConnect); } 1234567891011121314151617181920212223242526272829303132333435 1234567891011121314151617181920212223242526272829303132333435

    2. 发送消息

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

    3. 接收消息

    // 接收到<message> function onMessage(msg) { // 解析出<message>的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; } 12345678910111213 12345678910111213

    注意事项:  发送者与接收者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); }); });

    转载请注明原文地址: https://ju.6miu.com/read-678356.html

    最新回复(0)