第一次接触strophe,XMPP,和即时通讯项目。一第一次听说长轮询,长链接。
所以,一开始一脸懵逼,老板给了个strophe官方文档(http://strophe.im/strophejs/),无奈英文太差,还是一脸懵逼。好在浏览器能翻译整个网页。。。但是,既然连文档的一些方法名,属性名也翻译出来了,还是一脸懵逼;最后不得不一段一段翻译。
(个人建议:英文不太好的千万别作死学编程,不然就恶补英文。)
好了,讲正事,strophe是什么,不多解释了,还是自己去看文档吧。想要官方demo的话可以到这里下载(https://github.com/strophe/strophejs)
html代码
(如果涉及到跨域访问到问题需要去下载flXHR.js,strophe.flxhr.js的跨域脚本文件,下载地址(https://codeload.github.com/flensed/flXHR/zip/master))
<!DOCTYPE html>
<html>
<head>
<script src='http://cdn.bootcss.com/jquery/1.9.1/jquery.min.js'></script>
<script src='http://cdn.bootcss.com/strophe.js/1.1.3/strophe.min.js'></script>
<script src='test.js'></script>
</head>
<body>
JID:<input type="text" id="input-jid">
<br>
密码:<input type="password" id="input-pwd">
<br>
<button id="btn-login">登录</button>
<div id="msg" style="height: 400px; width: 400px; overflow: scroll;"></div>
<br>
消息:
<br>
<textarea id="input-msg" cols="30" rows="4"></textarea>
<br>
<button id="btn-send">发送</button>
</body>
</html>
test.js代码
/ XMPP服务器BOSH地址
var BOSH_SERVICE = 'http://192.168.1.204:5280/http-bind/';
// 房间JID
var ROOM_JID = 'fangjainhao@conference.192.168.1.204';
// XMPP连接
var connection = null;
// 当前状态是否连接
var connected = false;
// 当前登录的JID
var jid = "";
// 连接状态改变的事件
function onConnect(status) {
if (status == Strophe.Status.CONNFAIL) {
alert("连接失败!");
} else if (status == Strophe.Status.AUTHFAIL) {
alert("登录失败!");
} else if (status == Strophe.Status.DISCONNECTED) {
alert("连接断开!");
connected = false;
} else if (status == Strophe.Status.CONNECTED) {
alert("连接成功,可以开始聊天了!");
connected = true;
// 当接收到<message>节,调用onMessage回调函数
connection.addHandler(onMessage, null, 'message', null, null, null);
// 首先要发送一个<presence>给服务器(initial presence)
connection.send($pres().tree());
// 发送<presence>元素,加入房间
var pres = $pres({
from: jid,
to: ROOM_JID + "/" + jid.substring(0,jid.indexOf("@"))
}).c('x',{xmlns: 'http://jabber.org/protocol/muc'}).tree();
connection.send(pres);
//connection.sendIQ(pres);//获取房间列表
}
}
// 接收到<message>
function onMessage(msg) {
console.log(msg);
// 解析出<message>的from、type属性,以及body子元素
var from = msg.getAttribute('from');
var type = msg.getAttribute('type');
var elems = msg.getElementsByTagName('body');
if (type == "groupchat" && elems.length > 0) {
var body = elems[0];
$("#msg").append(from.substring(from.indexOf('/') + 1) + ":<br>" + Strophe.getText(body) + "<br>")
}
return true;
}
$(document).ready(function() {
// 通过BOSH连接XMPP服务器
$('#btn-login').click(function() {
if(!connected) {
connection = new Strophe.Connection(BOSH_SERVICE);
connection.connect($("#input-jid").val(), $("#input-pwd").val(), onConnect);
jid = $("#input-jid").val();
}
});
// 发送消息
$("#btn-send").click(function() {
if(connected) {
// 创建一个<message>元素并发送
var msg = $msg({
to: ROOM_JID,
from: jid,
type: 'groupchat'
}).c("body", null, $("#input-msg").val());
connection.send(msg.tree());
$("#input-msg").val('');
} else {
alert("请先登录!");
}
});
代码来源于:https://blog.csdn.net/yuruixin_china/article/details/76348812