在上一篇文章中,我们已经介绍如何用Openfire和jwchat构建webIM,但是我在搭建的过程中,总是感觉用户在登陆的时候速度非常慢,而且后期维护不好做
那么现在我在介绍一个比较简单的WebIM,在这个里面仅仅有几个简单的js,就可以完成和上面差不多的工作。
界面如下:
![](https://i-blog.csdnimg.cn/blog_migrate/fe494b8d17cc5f21b408be1b63c06dea.png)
首先介绍一下项目的目录结构
![](https://i-blog.csdnimg.cn/blog_migrate/e0780f696039a21005e2e5e2ca91cc26.png)
一、准备工作
jsjac JavaScript lib下载:http://download.csdn.net/detail/zwdsmileface/8595845
如果你不喜欢用jsjac JavaScript lib和Openfire通信,那么有一款jQuery的plugin可以供你使用,下载地址
jQuery-XMPP-plugin https://github.com/maxpowel/jQuery-XMPP-plugin
这里有所以能支持Openfire通信的第三方库,有兴趣的可以研究下 http://xmpp.org/xmpp-software/libraries/
jquery.easydrag 下载:http://fromvega.com/code/easydrag/jquery.easydrag.js
jquery 下载:http://code.jquery.com/jquery-1.7.1.min.js
JabberHTTPBind jhb.jar 下载:http://download.csdn.net/detail/ibm_hoojo/4489188
images 图片素材:http://download.csdn.net/detail/ibm_hoojo/4489439
二、核心代码演示
1、主界面(登陆、消息提示、日志、建立新聊天窗口)代码 index.jsp
<%@ page language="java" pageEncoding="UTF-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>WebIM Chat</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="author" content="hoojo">
<meta http-equiv="email" content="hoojo_@126.com">
<meta http-equiv="blog" content="http://blog.csdn.net/IBM_hoojo">
<meta http-equiv="blog" content="http://hoojo.cnblogs.com">
<link rel="stylesheet" type="text/css" href="css/chat-2.0.css" />
<script type="text/javascript">
window.contextPath = "<%=path%>";
window["serverDomin"] = "192.168.8.22";
</script>
<script type="text/javascript" src="jslib/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jslib/jsjac.js"></script>
<!-- script type="text/javascript" src="debugger/Debugger.js"></script-->
<script type="text/javascript" src="jslib/send.message.editor-1.0.js"></script>
<script type="text/javascript" src="jslib/jquery.easydrag.js"></script>
<script type="text/javascript" src="jslib/remote.jsjac.chat-2.0.js"></script>
<script type="text/javascript" src="jslib/local.chat-2.0.js"></script>
<script type="text/javascript">
$(function () {
$("#login").click(function () {
var userName = $(":text[name='userName']").val();
var receiver = $("*[name='to']").val();
// 建立一个聊天窗口应用,并设置发送者和消息接收者
$.WebIM({
sender: userName,
receiver: receiver
});
// 登陆到openfire服务器
remote.jsjac.chat.login(document.userForm);
$("label").text(userName);
$("form").hide();
$("#newConn").show();
});
$("#logout").click(function () {
// 退出openfire登陆,断开链接
remote.jsjac.chat.logout();
$("form").show();
$("#newConn").hide();
$("#chat").hide(800);
});
$("#newSession").click(function () {
var receiver = $("#sendTo").val();
// 建立一个新聊天窗口,并设置消息接收者(发送给谁?)
$.WebIM.newWebIM({
receiver: receiver
});
});
});
</script>
</head>
<body>
<!-- 登陆表单 -->
<form name="userForm" style="background-color: #fcfcfc; width: 100%;">
userName:<input type="text" name="userName" value="boy"/>
password:<input type="password" name="password" value="boy"/>
register: <input type="checkbox" name="register"/>
sendTo: <input type="text" id="to" name="to" value="hoojo" width="10"/>
<input type="button" value="Login" id="login"/>
</form>
<!-- 新窗口聊天 -->
<div id="newConn" style="display: none; background-color: #fcfcfc; width: 100%;">
User:<label></label>
sendTo: <input type="text" id="sendTo" value="hoojo" width="10"/>
<input type="button" value="new Chat" id="newSession"/>
<input type="button" value="Logout" id="logout"/>
</div>
<!-- 日志信息 -->
<div id="error" style="display: ; background-color: red;"></div>
<div id="info" style="display: ; background-color: #999999;"></div>
<!-- 聊天来消息提示 -->
<div class="chat-message">
<img src="images/write_icon.png" class="no-msg"/>
<img src="images/write_icon.gif" class="have-msg" style="display: none;"/>
</div>
</body>
</html>
下面这段代码尤为重要,它是设置你链接openfire的地址。这个地址一段错误你将无法进行通信!
<script type="text/javascript">
window.contextPath = "<%=path%>";
window["serverDomin"] = "192.168.8.22";
</script>
$.WebIM方法是主函数,用它可以覆盖local.chat中的基本配置,它可以完成聊天窗口的创建。$.WebIM.newWebIM方法是新创建一个窗口,只是消息的接收者是一个新用户。
$.WebIM({
sender: userName,
receiver: receiver
});
$.WebIM.newWebIM({
receiver: receiver
});
remote.jsjac.chat.login(document.userForm);方法是用户登录到Openfire服务器
参数如下:
httpbase: window.contextPath + "/JHB/", //请求后台http-bind服务器url
domain: window["serverDomin"], //"192.168.5.231", // 192.168.5.231 当前有效域名
username: "", // 登录用户名
pass: "", // 密码
timerval: 2000, // 设置请求超时
resource: "WebIM", // 链接资源标识
register: true // 是否注册
remote.jsjac.chat.logout();是退出、断开openfire的链接
2、本地聊天应用核心代码 local.chat-2.0.js
/***
* jquery local chat
* @version v2.0
* @createDate -- 2012-5-28
* @author hoojo
* @email hoojo_@126.com
* @blog http://hoojo.cnblogs.com & http://blog.csdn.net/IBM_hoojo
* @requires jQuery v1.2.3 or later, send.message.editor-1.0.js
* Copyright (c) 2012 M. hoo
**/
;(function ($) {
if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
alert('WebIM requires jQuery v1.2.3 or later! You are using v' + $.fn.jquery);
return;
}
var faceTimed, count = 0;
var _opts = defaultOptions = {
version: 2.0,
chat: "#chat",
chatEl: function () {
var $chat = _opts.chat;
if ((typeof _opts.chat) == "string") {
$chat = $(_opts.chat);
} else if ((typeof _opts.chat) == "object") {
if (!$chat.get(0)) {
$chat = $($chat);
}
}
return $chat;
},
sendMessageIFrame: function (receiverId) {
return $("iframe[name='sendMessage" + receiverId + "']").get(0).contentWindow;
},
receiveMessageDoc: function (receiverId) {
receiverId = receiverId || "";
var docs = [];
$.each($("iframe[name^='receiveMessage" + receiverId + "']"), function () {
docs.push($(this.contentWindow.document));
});
return docs;
//return $($("iframe[name^='receiveMessage" + receiverId + "']").get(0).contentWindow.document);
},
sender: "", // 发送者
receiver: "", // 接收者
setTitle: function (chatEl) {
var receiver = this.getReceiver(chatEl);
chatEl.find(".title").html("和" + receiver + "聊天对话中");
},
getReceiver: function (chatEl) {
var receiver = chatEl.attr("receiver");
if (~receiver.indexOf("@")) {
receiver = receiver.split("@")[0];
}
return receiver;
},
// 接收消息iframe样式
receiveStyle: [
'<html>',
'<head><style type="text/css">',
'body{border:0;margin:0;padding:3px;height:98%;cursor:text;background-color:white;font-size:12px;font-family:Courier,serif,monospace;}',
'.msg{margin-left: 1em;}p{margin:0;padding:0;}.me{color: blue;}.you{color:green;}',
'</style></head>',
'<body></body>',
'</html>'
].join(""),
writeReceiveStyle: function (receiverId) {
this.receiveMessageDoc(receiverId)[0].get(0).write(this.receiveStyle);
},
datetimeFormat: function (v) {
if (~~v < 10) {
return "0" + v;
}
return v;
},
getDatetime: function () {
// 设置当前发送日前
var date = new Date();
var datetime = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
datetime = " " + _opts.datetimeFormat(date.getHours())
+ ":" + _opts.datetimeFormat(date.getMinutes())
+ ":" + _opts.datetimeFormat(date.getSeconds());
return datetime;
},
/***
* 发送消息的格式模板
* flag = true 表示当前user是自己,否则就是对方
**/
receiveMessageTpl: function (userName, styleTpl, content, flag) {
var userCls = flag ? "me" : "you";
if (styleTpl && flag) {
content = [ "<span style='", styleTpl, "'>", content, "</span>" ].join("");
}
return [
'',
'<p class="msg">', content, ''
].join("");
},
// 工具类按钮触发事件返回html模板
sendMessageStyle: {
cssStyle: {
bold: "font-weight: bold;",
underline: "text-decoration: underline;",
italic: "font-style: oblique;"
},
setStyle: function (style, val) {
if (val) {
_opts.sendMessageStyle[style] = val;
} else {
var styleVal = _opts.sendMessageStyle[style];
if (styleVal === undefined || !styleVal) {
_opts.sendMessageStyle[style] = true;
} else {
那么现在我在介绍一个比较简单的WebIM,在这个里面仅仅有几个简单的js,就可以完成和上面差不多的工作。
界面如下:
![](https://i-blog.csdnimg.cn/blog_migrate/fe494b8d17cc5f21b408be1b63c06dea.png)
首先介绍一下项目的目录结构
![](https://i-blog.csdnimg.cn/blog_migrate/e0780f696039a21005e2e5e2ca91cc26.png)
一、准备工作
jsjac JavaScript lib下载:http://download.csdn.net/detail/zwdsmileface/8595845
如果你不喜欢用jsjac JavaScript lib和Openfire通信,那么有一款jQuery的plugin可以供你使用,下载地址
jQuery-XMPP-plugin https://github.com/maxpowel/jQuery-XMPP-plugin
这里有所以能支持Openfire通信的第三方库,有兴趣的可以研究下 http://xmpp.org/xmpp-software/libraries/
jquery.easydrag 下载:http://fromvega.com/code/easydrag/jquery.easydrag.js
jquery 下载:http://code.jquery.com/jquery-1.7.1.min.js
JabberHTTPBind jhb.jar 下载:http://download.csdn.net/detail/ibm_hoojo/4489188
images 图片素材:http://download.csdn.net/detail/ibm_hoojo/4489439
二、核心代码演示
1、主界面(登陆、消息提示、日志、建立新聊天窗口)代码 index.jsp
<%@ page language="java" pageEncoding="UTF-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>WebIM Chat</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="author" content="hoojo">
<meta http-equiv="email" content="hoojo_@126.com">
<meta http-equiv="blog" content="http://blog.csdn.net/IBM_hoojo">
<meta http-equiv="blog" content="http://hoojo.cnblogs.com">
<link rel="stylesheet" type="text/css" href="css/chat-2.0.css" />
<script type="text/javascript">
window.contextPath = "<%=path%>";
window["serverDomin"] = "192.168.8.22";
</script>
<script type="text/javascript" src="jslib/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jslib/jsjac.js"></script>
<!-- script type="text/javascript" src="debugger/Debugger.js"></script-->
<script type="text/javascript" src="jslib/send.message.editor-1.0.js"></script>
<script type="text/javascript" src="jslib/jquery.easydrag.js"></script>
<script type="text/javascript" src="jslib/remote.jsjac.chat-2.0.js"></script>
<script type="text/javascript" src="jslib/local.chat-2.0.js"></script>
<script type="text/javascript">
$(function () {
$("#login").click(function () {
var userName = $(":text[name='userName']").val();
var receiver = $("*[name='to']").val();
// 建立一个聊天窗口应用,并设置发送者和消息接收者
$.WebIM({
sender: userName,
receiver: receiver
});
// 登陆到openfire服务器
remote.jsjac.chat.login(document.userForm);
$("label").text(userName);
$("form").hide();
$("#newConn").show();
});
$("#logout").click(function () {
// 退出openfire登陆,断开链接
remote.jsjac.chat.logout();
$("form").show();
$("#newConn").hide();
$("#chat").hide(800);
});
$("#newSession").click(function () {
var receiver = $("#sendTo").val();
// 建立一个新聊天窗口,并设置消息接收者(发送给谁?)
$.WebIM.newWebIM({
receiver: receiver
});
});
});
</script>
</head>
<body>
<!-- 登陆表单 -->
<form name="userForm" style="background-color: #fcfcfc; width: 100%;">
userName:<input type="text" name="userName" value="boy"/>
password:<input type="password" name="password" value="boy"/>
register: <input type="checkbox" name="register"/>
sendTo: <input type="text" id="to" name="to" value="hoojo" width="10"/>
<input type="button" value="Login" id="login"/>
</form>
<!-- 新窗口聊天 -->
<div id="newConn" style="display: none; background-color: #fcfcfc; width: 100%;">
User:<label></label>
sendTo: <input type="text" id="sendTo" value="hoojo" width="10"/>
<input type="button" value="new Chat" id="newSession"/>
<input type="button" value="Logout" id="logout"/>
</div>
<!-- 日志信息 -->
<div id="error" style="display: ; background-color: red;"></div>
<div id="info" style="display: ; background-color: #999999;"></div>
<!-- 聊天来消息提示 -->
<div class="chat-message">
<img src="images/write_icon.png" class="no-msg"/>
<img src="images/write_icon.gif" class="have-msg" style="display: none;"/>
</div>
</body>
</html>
下面这段代码尤为重要,它是设置你链接openfire的地址。这个地址一段错误你将无法进行通信!
<script type="text/javascript">
window.contextPath = "<%=path%>";
window["serverDomin"] = "192.168.8.22";
</script>
$.WebIM方法是主函数,用它可以覆盖local.chat中的基本配置,它可以完成聊天窗口的创建。$.WebIM.newWebIM方法是新创建一个窗口,只是消息的接收者是一个新用户。
$.WebIM({
sender: userName,
receiver: receiver
});
$.WebIM.newWebIM({
receiver: receiver
});
remote.jsjac.chat.login(document.userForm);方法是用户登录到Openfire服务器
参数如下:
httpbase: window.contextPath + "/JHB/", //请求后台http-bind服务器url
domain: window["serverDomin"], //"192.168.5.231", // 192.168.5.231 当前有效域名
username: "", // 登录用户名
pass: "", // 密码
timerval: 2000, // 设置请求超时
resource: "WebIM", // 链接资源标识
register: true // 是否注册
remote.jsjac.chat.logout();是退出、断开openfire的链接
2、本地聊天应用核心代码 local.chat-2.0.js
/***
* jquery local chat
* @version v2.0
* @createDate -- 2012-5-28
* @author hoojo
* @email hoojo_@126.com
* @blog http://hoojo.cnblogs.com & http://blog.csdn.net/IBM_hoojo
* @requires jQuery v1.2.3 or later, send.message.editor-1.0.js
* Copyright (c) 2012 M. hoo
**/
;(function ($) {
if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
alert('WebIM requires jQuery v1.2.3 or later! You are using v' + $.fn.jquery);
return;
}
var faceTimed, count = 0;
var _opts = defaultOptions = {
version: 2.0,
chat: "#chat",
chatEl: function () {
var $chat = _opts.chat;
if ((typeof _opts.chat) == "string") {
$chat = $(_opts.chat);
} else if ((typeof _opts.chat) == "object") {
if (!$chat.get(0)) {
$chat = $($chat);
}
}
return $chat;
},
sendMessageIFrame: function (receiverId) {
return $("iframe[name='sendMessage" + receiverId + "']").get(0).contentWindow;
},
receiveMessageDoc: function (receiverId) {
receiverId = receiverId || "";
var docs = [];
$.each($("iframe[name^='receiveMessage" + receiverId + "']"), function () {
docs.push($(this.contentWindow.document));
});
return docs;
//return $($("iframe[name^='receiveMessage" + receiverId + "']").get(0).contentWindow.document);
},
sender: "", // 发送者
receiver: "", // 接收者
setTitle: function (chatEl) {
var receiver = this.getReceiver(chatEl);
chatEl.find(".title").html("和" + receiver + "聊天对话中");
},
getReceiver: function (chatEl) {
var receiver = chatEl.attr("receiver");
if (~receiver.indexOf("@")) {
receiver = receiver.split("@")[0];
}
return receiver;
},
// 接收消息iframe样式
receiveStyle: [
'<html>',
'<head><style type="text/css">',
'body{border:0;margin:0;padding:3px;height:98%;cursor:text;background-color:white;font-size:12px;font-family:Courier,serif,monospace;}',
'.msg{margin-left: 1em;}p{margin:0;padding:0;}.me{color: blue;}.you{color:green;}',
'</style></head>',
'<body></body>',
'</html>'
].join(""),
writeReceiveStyle: function (receiverId) {
this.receiveMessageDoc(receiverId)[0].get(0).write(this.receiveStyle);
},
datetimeFormat: function (v) {
if (~~v < 10) {
return "0" + v;
}
return v;
},
getDatetime: function () {
// 设置当前发送日前
var date = new Date();
var datetime = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
datetime = " " + _opts.datetimeFormat(date.getHours())
+ ":" + _opts.datetimeFormat(date.getMinutes())
+ ":" + _opts.datetimeFormat(date.getSeconds());
return datetime;
},
/***
* 发送消息的格式模板
* flag = true 表示当前user是自己,否则就是对方
**/
receiveMessageTpl: function (userName, styleTpl, content, flag) {
var userCls = flag ? "me" : "you";
if (styleTpl && flag) {
content = [ "<span style='", styleTpl, "'>", content, "</span>" ].join("");
}
return [
'',
'<p class="msg">', content, ''
].join("");
},
// 工具类按钮触发事件返回html模板
sendMessageStyle: {
cssStyle: {
bold: "font-weight: bold;",
underline: "text-decoration: underline;",
italic: "font-style: oblique;"
},
setStyle: function (style, val) {
if (val) {
_opts.sendMessageStyle[style] = val;
} else {
var styleVal = _opts.sendMessageStyle[style];
if (styleVal === undefined || !styleVal) {
_opts.sendMessageStyle[style] = true;
} else {