Strophe第一步 hello world

本文介绍如何使用XMPP协议中的BOSH功能实现HTTP方式连接服务器,并通过Strophe.js库进行连接及Ping操作流程。文章还强调了在连接时主机名需与JID中的主机名一致。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

XMPP协议中的BOSH是 XMPP server 对外提供的可以支持 http直接访问服务器,一般是是基于长轮询的。

openfire中也提供了这个功能,默认是关闭的需要打开。



后面我们将通过http://host:7070/http-bind/地址来进行连接,这里要特别提一下,这个host,在xmpp中的 jid     即账户    比如  a@host  要保持一致,不然 连接将会失败,你可以在本机的host的配置文件上加上如果openfire在你的本机上的话

这里我将利用Strophe.js库进行连接

一下是部分核心代码

var conn = new Strophe.Connection("http://host:7070/http-bind/");

conn.connect(data.jid, data.password, function (status) {
        if (status === Strophe.Status.CONNECTED) {
            $(document).trigger('connected');
        } else if (status === Strophe.Status.DISCONNECTED) {
            $(document).trigger('disconnected');
        }
 });


$(document).bind('connected', function () {
    // inform the user
    Hello.log("Connection established.");
    Hello.connection.addHandler(Hello.handle_pong, null, "iq", null, "ping1");
    var domain = Strophe.getDomainFromJid(Hello.connection.jid);
    Hello.send_ping(domain);
});


$(document).bind('disconnected', function () {
    Hello.log("Connection terminated.");
    // remove dead connection object
    Hello.connection = null;
});

send_ping: function (to) {
        var ping = $iq({to: to, type: "get", id: "ping1"}).c("ping", {xmlns: "urn:xmpp:ping"});


        Hello.log("Sending ping to " + to + ".");


        Hello.start_time = (new Date()).getTime();
        Hello.connection.send(ping);
    },


    handle_pong: function (iq) {
        var elapsed = (new Date()).getTime() - Hello.start_time;
        Hello.log("Received pong from server in " + elapsed + "ms.");


        Hello.connection.disconnect();
        
        return false;
    }


以上很简单就是一个 ping server的过程。


评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值