博主CSDN昵稱:守護(hù)者ly,歡迎大家前去指點
最近寫了一個Node.js使用node-xmpp的例子,實現(xiàn)了登錄、收發(fā)消息和消息的解析,貼出來與大家參詳一下。
我使用的node-xmpp版本為1.0.4,在創(chuàng)建好node.js項目后,可以運(yùn)行npm install node-xmpp進(jìn)行安裝,在此我就不再贅述了。實現(xiàn)通信還需要配置ejabberd服務(wù)器,這個網(wǎng)上有資料,請自行谷歌。
將node-xmpp引入項目后,首先聲明變量
//version 1.0.4
var XMPP = require('node-xmpp');
接下來配置連接屬性
var cl = new XMPP.Client({
//用戶名
jid: 'lf@h.com',
//密碼
password: '111111',
reconnect: true,
//ejabberd服務(wù)器地址
host: '192.168.26.38',
//端口號
port: '5222'
});
然后就可以登錄了。我下面的代碼實現(xiàn)了登陸后向一個名為“ly@h.com”人發(fā)送一條"fighting!"的消息,然后開啟接收消息的監(jiān)聽
// Do things when online
cl.on('online', function () {
console.log("We're online!");
// Set client's presence
cl.send(new XMPP.Element('presence', {type: 'available'}).c('show').t('chat'));
// Send keepalive
setInterval(function () {
cl.send(' ');
}, 30000);
var chatMessage = new XMPP.Element('message', {to: 'ly@h.com', type:'chat'})
//添加名為body的標(biāo)簽,并設(shè)置內(nèi)容為fighting! up()表示添加的標(biāo)簽不作為子標(biāo)簽
.c('body').t('fighting!').up()
//添加名為userinfo的標(biāo)簽,與body標(biāo)簽同級別
.c('userinfo', {'xmlns':'extension'})
//添加作為userinfo子標(biāo)簽的名為name的標(biāo)簽
.c('name').t("lf");
cl.send(chatMessage.tree());
//監(jiān)聽方法
cl.on('stanza', function(message) {
console.log('message get'+ message);
//此if判斷無效
if(message.attr.type == 'message'){
console.log('ok');
}
if(message.is('message')){
console.log('get');
console.log("type = " + message.type);
var userinfo = message.getChild('userinfo');
var name;
if(userinfo != null){
name = userinfo.getChild('name');
console.log("name = "+name);
if(name != null){
console.log("name text = " + name.getText());
}
}
console.log("body = " + message.getChild('body').getText());
}
});
});
在接收端接收到的消息內(nèi)容如下:
<message to='ly@h.com' from='lf@h.com/14713727713775752643754' type='chat'><body>fighting!</body><thread>376fd9b5-c908-4b04-a7ae-9e3bc6f07265</thread><userinfo xmlns='extension'><name>lf</name></userinfo></message>
其中接到的消息message,可以使用"message.from"獲取到消息的發(fā)送人,使用"message.getChild('body')“方法獲取到消息內(nèi)容。我在Android端發(fā)送消息時又新增了名為"userinfo"的標(biāo)簽,又在其中加入了name標(biāo)簽,android端消息代碼如下:
Message message = new Message("lf@h.com");
message.addBody(null, "I must be willing to fight!");
message.addSubject("favorite color", "red");
DefaultExtensionElement defaultExtensionElement = new DefaultExtensionElement(
"userinfo","extension");
defaultExtensionElement.setValue("name","ly");
message.addExtension(defaultExtensionElement);
ly@h.com用戶向lf@h.com回復(fù)了一條"I must be willing to fight!"并在name標(biāo)簽中署名ly。具體接收到的消息如下:
<message from="ly@h.com/Smack" to="lf@h.com" xml:lang="en" id="gMXeR-15" type="chat" xmlns:stream="http://etherx.jabber.org/streams"><subject xml:lang="favorite color">red</subject><body>I must be willing to fight!</body><thread>8902450d-4624-484c-8b0e-454db8243750</thread><userinfo xmlns="extension"><name>ly</name></userinfo></message>
以上并非全部node.js代碼,但是關(guān)鍵方法已經(jīng)給出,用興趣的朋友可以試試。如有不足之處,請大家不吝指教!