转自:http://blog.csdn.net/xundh/article/details/52419694
文档: http://strophe.im/strophejs/doc/1.2.6/files/strophe-js.html
1. 与服务器建立连接
var BOSH_SERVICE
= 'http://pc-20160820rwic:7070/http-bind/';
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;
connection
.addHandler(onMessage,
null,
'message',
null,
null,
null);
connection
.send(
$pres()
.tree());
}
}
if(
!connected) {
connection
= new Strophe
.Connection(BOSH_SERVICE);
connection
.connect(jid, password, onConnect);
}
1234567891011121314151617181920212223242526272829303132333435
1234567891011121314151617181920212223242526272829303132333435
2. 发送消息
var msg
= $msg({
to: toJid,
from: fromJid,
type:
'chat'
})
.c(
"body",
null, 要发送的内容);
connection
.send(msg
.tree());
123456789
123456789
3. 接收消息
function onMessage(msg) {
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');
console.log(
'jid',jid);
});
});
转载请注明原文地址: https://ju.6miu.com/read-678356.html