/* * 参考《XMPP高级编程+使用JavaScript和jQuery》第三章例子。 * 我修改了作者的XMPP服务器到本地的openfire。JavaScript跨域请求,使用Nginx代理。另外,添加了些备注笔记。 * * 几个概念 * * 1) BOSH(Bidirectional streams Over Synchronous HTTP,在同步HTTP之上传送双向数据流),是一种XMPP的长轮询桥接技术 * 2) Comet(反向HTTP),同上也是长轮询一种 * 3) 很多XMPP服务器都内置了对BOSH的支持,这种服务叫做“BOSH连接管理器”,通常以URL http://example.com:5280/http-bind或者http://example.com:5280/xmpp-httpbind来提供服务。 * 4) 书上的连接管理器的测试URL为http://bosh.metajack.im:5280/xmpp-httpbind * */ //命名空间对象(存储应用程序状态和全局变量) var myNamespace = { some_global: 0, another_global: true, my_adder: function(x, y){ return x+y; } }; // 创建自己的命名空间对象Hello var Hello = { connection: null, start_time: null, // 输出日志 log: function(msg){ $('#log').append(""+msg+"
"); }, // 定义打招呼用的节内容,并连接server。连接成功以后调用handler操作。 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); }, // 连接后的handler方法 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;//不销毁 } } // XMPP连接通过Strophe.Connection对象管理 $(document).ready(function(){ // 控制出发按钮,就出现id为login_dialog的div $('#login_dialog').dialog({ autoopen: true, draggable: false, modal: true, title: 'Connect to XMPP', buttons: { "Connect": function(){ $(document).trigger('connect', {//启动connect自定义事件,传入jid和password jid: $('#jid').val(), password: $('#password').val() }); $('#password').val('');// 一旦触发,密码口令被清空 $(this).dialog('close'); } } }); // 1) 处理XMPP的connect事件,即创建Strophe.Connection对象并调用connect()方法。 // 2) 提供一个能够相应连接状态变化的回调函数 $(document).bind('connect', function(ev, data){ // var conn = new Strophe.Connection("http://bosh.metajack.im:5280/xmpp-httpbind"); var conn = new Strophe.Connection("http://timelyxyzmacbookpro.local: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'); } }); Hello.connection = conn; }); $(document).bind('connected', function(){ Hello.log("Connection established.");// 通知用户 Hello.connection.addHandler(Hello.handle_pong, null, "iq", null, "ping1");// handler在send_ping里的send完成之后立马执行,此处只是提前声明handler var domain = Strophe.getDomainFromJid(Hello.connection.jid); console.log(domain); Hello.send_ping(domain); }); $(document).bind('disconnected', function(){ Hello.log("Connection terminated."); Hello.connection = null;// 释放已销毁的connection对象引用 }); });