效果图
包含的技术
* 基本的HTML+CSS+DIV+JavaScript
* Jquery
* Node.js
* H5 WebSocket
实现步骤
准备背景图片(自选)
创建目录结构如下
安装nodejs-websocket
下载命令:npm install https://github.com/sitegui/nodejs-websocket
如下:
实现代码
createUUID.js
/** 生成伪UUID:代码源自网络 **/
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
Math.uuid = function(len, radix) {
var chars = CHARS,
uuid = [],
i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
var r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
};
index.css
body{ background-image: url("img/bg/1.jpg"); }
/*============== 标题和页脚 =============*/
.title,.foot{margin-top: 3%; text-align: center; }
/*============== 聊天室div =============*/
.chat-div{width: 800px; height: 730px; margin: 0 auto; }
fieldset{
height: 95%;
position: relative;
border: none;
}
legend{ color:red; }
/*============== 消息窗口 =============*/
.msg-div{
background-color: white;
border-radius: 5px;
height: 85%;
padding: 8px 20px;
overflow-y: auto;
}
.msg-div div{margin-bottom: 5px; }
.msg-div span{margin-left: 45%; font-size: 5px; }
/*名字颜色*/
.nameColor1,
.nameColor2,
.nameColor3,
.nameColor4,
.nameColor5{
width: 65px;
border-radius: 8px;
text-align: center;
}
.nameColor1{background-color: lightgreen; }
.nameColor2{background-color: steelblue; }
.nameColor3{background-color: tomato; }
.nameColor4{background-color: lightsalmon; }
.nameColor5{background-color: lightsteelblue; }
.my>div{text-align: right; }
/*============== 发送窗口 =============*/
.send-div{
/* 绝对定位参照上一个相对定位或最顶层元素 */
position: absolute;
bottom: 0px;
height: 80px;
width: 97%;
line-height: 80px;
/*border: 1px solid black;*/
}
.send-div input{
display: inline-block;
border-radius: 5px;
height: 50px;
width: 81%;
font-size: 20px;
padding-left: 10px;
}
.send-div button{
display: inline-block;
border-radius: 5px;
height: 55px;
width: 15%;
margin-left: 10px;
font-size: 20px;
background-color: Black;
color: Azure;
/*透明*/
opacity: 0.8;
border: 1.8px solid rgba(0,0,0,1);
}
/*============== 登录提示窗口 =============*/
.loginMsg-div{
position: absolute;
/*border: 1px solid rgba(0,0,0,0.1);*/
height: 700px;
width: 350px;
left: 4%;
top: 10%;
padding-left: 25px;
color: black;
font-size: 23px;
overflow-y: auto;
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>chat3.0</title>
<!-- css -->
<link rel="stylesheet" type="text/css" href="index.css" />
<!-- jquery -->
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<!-- uuid js -->
<script type="text/javascript" src="createUUID.js"></script>
</head>
<body>
<div class="title">
<h1>实时聊天室3.0</h1>
</div>
<div class="chat-div">
<fieldset>
<legend>当前在线人数:<span id="count"></span></legend>
<!-- 接受信息窗口 -->
<div class="msg-div">
<!-- 测试:聊天信息 -->
<!-- other
<div>
<span class="time">13:17:05</span>
<div>
<div class="nameColor1">张三丰:</div>
<div>hello!!!</div>
</div>
</div>
<div>
<span class="time">13:17:05</span>
<div>
<div class="nameColor2">张三丰:</div>
<div>hello!!!</div>
</div>
</div>
-->
<!-- my
<div class="my">
<span class="time">13:17:16</span>
<div>
<div>hi</div>
</div>
</div>
-->
</div>
<!-- 发送信息窗口 -->
<div class="send-div">
<input type="text" id="message" autofocus>
<button id="send">send</button>
</div>
</fieldset>
</div>
<!-- 页脚 -->
<div class="foot">
<h3 id="username"></h3>
</div>
<!-- 进入聊天室提示窗口 -->
<div class="loginMsg-div"> </div>
</body>
<!-- index js -->
<script type="text/javascript" src="index.js"></script>
</html>
index.js
// 初始化用户信息
$(function(){
// 获取UUID
local_uuid = Math.uuid();
//用户信息
userObject = {};
userObject.local_uuid = local_uuid; //用户标识
userObject.cssStyle = "nameColor" + Math.floor(Math.random() * 5 + 1);; //随机生成名字的class样式后缀(在对方浏览器显示)
var username = window.prompt("请输入你这次聊天的网名",""); //获取用户名称
if(username){ //初始化名称
userObject.username = username;
$("#username").html(username);
}else{
userObject.username = "匿名用户";
$("#username").html("匿名用户");
}
userObject.sayhi = "sayhi"; //进入聊天室标记,该标记刚进入聊天室才生效
});
// websocket操作
$(function(){
//创建websocket对象
websocket = new WebSocket("ws://localhost:8001");
//连接成功后触发
websocket.onopen = function(){
//连接成功,要求服务器广播进入聊天室信息
sendUserIntoMsg();
//发送信息
$("#send").click(sendMsg);
$("#message").keypress(function(event){
if(event.keyCode ==13){
sendMsg();
}
});
}
//接收到服务器响应时触发
websocket.onmessage = function(res){
data = JSON.parse(res.data);
if(isNaN(data.count)){
user = data;
if(user.sayhi == "sayhi"){ //刚进入聊天室
newElement = createUserIntoMsgDiv(user.username, user.snedtime);
$(".loginMsg-div").append(newElement);
} else {
if(user.local_uuid == local_uuid){ //当前用户发出的消息
newElement = createMyMsgDiv(user.message, user.snedtime);
} else { //其他用户发出的消息
newElement = createOtherMsgDiv(user.username, user.message, user.snedtime, user.cssStyle);
}
$(".msg-div").append(newElement);
//将消息窗口的滚动条移动到最低
$(".msg-div").scrollTop( $(".msg-div")[0].scrollHeight );
}
} else {
$("#count").html(data.count);
}
}
});
//发送消息
function sendMsg(){
//将发送内容封装到用户对象中
var text = $("#message").val();
if(!text) {
alert("请输入聊天内容再发送!!!");
return;
}
userObject.message = text;
userObject.sayhi = "";
var date = new Date();
userObject.sendtime = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "";
userJson = JSON.stringify(userObject); //将对象转为json串
websocket.send(userJson); //发送消息
$("#message").val("");
$("#message").focus();
}
//发送用户进入聊天室消息
function sendUserIntoMsg(){
var date = new Date();
userObject.snedtime = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "";
userJson = JSON.stringify(userObject);
websocket.send(userJson);
}
// 创建进入聊天室信息
function createUserIntoMsgDiv(name, time){
return $("<div>").html("<div> [" + user.username + "] " + user.snedtime + " 进入聊天室!!!!!</div>");
}
// 创建我的消息
function createMyMsgDiv(msg, time){
return $("<div>").html("<span>" + time + "</span> <div>" + msg + "</div>").addClass("my");
}
// 创建其他用户的消息
function createOtherMsgDiv(name, msg, time, css){
return $("<div>").html("<span>" + time + "</span> <div class="+ css +">" + name + "</div> <div>" + msg + "</div>");
}
//禁止右键
$(function() {
$(document).bind("contextmenu",function(e) {
alert("sorry!!! No right-clicking!");
return false;
});
});
server.js [node.js]
//引入websocket模块
var ws = require("nodejs-websocket");
//在线人数
count = 0;
var server = ws.createServer(function (conn) {
//接收到客户端信息时触发
conn.on("text", function (reqUserJson) {
broadcast(conn, reqUserJson);
});
//退出人数统计
conn.on("close", function (code, reason) {
--count;
broadcast(conn, countUser(count));
});
conn.on("error", function(error){
console.log("error...");
});
}).listen(8001);
//登录人数统计
server.on("connection", function(conn){
++count;
broadcast(conn, countUser(count));
});
//向客户端广播接收到的消息
function broadcast(conn, resData){
server.connections.forEach(function (conn) {
conn.sendText(resData);
})
}
//统计在线人数
function countUser(count){
var obj = {"count":count};
var countJson = JSON.stringify(obj);
return countJson;
}