简易聊天室代码分享 js+socket.io
Posted 北极光之夜。
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简易聊天室代码分享 js+socket.io相关的知识,希望对你有一定的参考价值。
先言
这我以前写的,这里就是单纯分享下代码,不算正经文章。效果如下,前端用一个单html文件。然后后端用node.js和socket.io,也是只用一个单js文件就好。这里可以看下代码的实现逻辑就好,因为来连数据库才能运行的。有需要的话告诉我,我也可以把存取数据库代码逻辑和接口逻辑删了,改成时时存时时失效的,这样就能直接打开html文件直接随意运行了。
代码
前端:
html:
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO chat</title>
<link rel="stylesheet" href="./chat.css" />
</head>
<body>
<img class="bg" src="../bg.webp" alt="" />
<div class="chat">
<div class="left">
<div class="title">
<h3>聊天室</h3>
</div>
<div class="content" id="content">
<div class="history" id="history">
<button>查看最近的聊天</button>
</div>
<ul id="messages">
<!-- <li class="data">
<div class="img">
<img
src="https://bbs-img.huaweicloud.com/user/img/head/1617968414164_1201_6320.jpg"
alt=""
/>
</div>
<p><span>小杰(老师):</span> 【摘要】</p>
</li>
<li class="data2">
<p>
<span>我:</span> 【摘要】
首先,强类型不允许随意的隐式类型转换,而弱类型是允许的。javascript就是经典的弱类型语言。而Typescript可以说是JavaScript的超集,在js的基础上新增了许多语法特性,使得类型不再可以随意转换,能大大减少开发阶段的错误。
</p>
<div class="img">
<img
src="https://bbs-img.huaweicloud.com/user/img/head/1617968414164_1201_6320.jpg"
alt=""
/>
</div>
</li> -->
</ul>
</div>
<div class="shuru">
<textarea
id="m"
type="text"
autocomplete="off"
autofocus=""
></textarea>
<button id="btn">
发送
</button>
<div class="emoji" id="emoji">
😊
<div id="ej" style="display: none;">
<span>😂</span>
<span>😐</span>
<span>😤</span>
<span>😴</span>
<span>😫</span>
<span>😧</span>
<span>🤪</span>
<span>😛</span>
<span>😭</span>
<span>😡</span>
<span>👹</span>
<span>🤢</span>
<span>❤️</span>
<span>💔</span>
<span>👄</span>
<span>🧝</span>
<span>💇♀️</span>
<span>💘</span>
<span>👻</span>
<span>☠️</span>
<span>😱</span>
<span>🌬️</span>
<span>👌</span>
<span>🤝</span>
</div>
</div>
</div>
</div>
<div class="right">
<div class="title">
<h3>当前在线成员<span id="people">(0)</span></h3>
</div>
<div class="list" id="list">
<!-- <div class="item">
<img
src="https://bbs-img.huaweicloud.com/user/img/head/1617968414164_1201_6320.jpg"
alt=""
/>
<p>小杰(学生)33333330000</p>
</div> -->
</div>
</div>
</div>
</body>
<!-- <script src="https://unpkg.com/axios/dist/axios.min.js"></script> -->
<script>
// 封装的ajax请求
function ajax(url, params)
return new Promise((resolve, reject) =>
//要发个get请求知道是你来了,后端解析你的信息
let xhr = new XMLHttpRequest();
// 设置属性
xhr.open("post", url);
// 如果想要使用post提交数据,必须添加此行
xhr.setRequestHeader(
"Content-type",
"application/x-www-form-urlencoded"
);
// 将数据通过send方法传递
xhr.send(params);
// 发送并接受返回值
xhr.onreadystatechange = function()
// 这步为判断服务器是否正确响应
if (xhr.readyState == 4 && xhr.status == 200)
resolve(xhr.responseText);
;
);
</script>
<script src="./static/dist/socket.io.js"></script>
<script>
//要发个请求知道是你来了,后端解析你的信息
/* axios
.post("http://localhost:8849/",
username: "787",
)
.then(function(response)
console.log(response);
); */
let net_name = window.sessionStorage.getItem("net_name");
let icon = window.sessionStorage.getItem("icon");
let role = window.sessionStorage.getItem("role");
let uid = window.sessionStorage.getItem("uid");
if (role == "1")
role = "学生";
else if (role == "2")
role = "老师";
else
role = "管理员";
/* let uid = Number(
Math.random()
.toString()
.substr(3, 10) + Date.now()
).toString(36); */
ajax(
"http://localhost:8849/",
`net_name=$net_name&icon=$icon&role=$role&uid=$uid`
).then(function(response)
console.log(response);
);
// 做个判断
var socket = io("http://localhost:8849/");
var btn = document.getElementById("btn");
var ul = document.getElementById("messages");
let cxt = document.getElementById("m");
let people = document.getElementById("people");
let content = document.getElementById("content");
let list = document.getElementById("list");
let history = document.getElementById("history");
let emoji = document.getElementById("emoji");
let ej = document.getElementById("ej");
//选表情
emoji.onclick = function(e)
if (ej.style.display == "block")
ej.style.display = "none";
else
ej.style.display = "block";
;
ej.onclick = function(e)
// console.log(e.target.innerText);
if (e.target.nodeName.toLowerCase() == "span")
cxt.value += e.target.innerText;
;
history.onclick = function()
//查看历史记录
history.style.display = "none";
ajax("http://localhost:8849/query", "").then(function(response)
let data = JSON.parse(response).data;
//先看下有几个小li了
lis = document.getElementById("messages").getElementsByTagName("li")
.length;
console.log(lis);
for (let i = lis; i < data.length - 1; i++)
let newli = document.createElement("li");
if (data[i].uid == uid)
newli.setAttribute("class", "data2");
newli.innerHTML = `
<p>
<span>$data[i].net_name($data[i].role):</span> $data[i].content
</p>
<div class="img">
<img
src="http://localhost:8848/$data[i].icon"
alt=""
/>
</div>
`;
else
newli.setAttribute("class", "data");
newli.innerHTML = `
<div class="img">
<img
src="http://localhost:8848/$data[i].icon"
alt=""
/>
</div>
<p>
<span>$data[i].net_name($data[i].role):</span> $data[i].content
</p>`;
ul.insertBefore(newli, ul.childNodes[0]);
//滚动到底部
content.scrollTo(
top: content.scrollHeight,
behavior: "smooth",
);
);
;
// 点击send按钮,把消息发送给服务器
btn.onclick = function()
if (cxt.value == "") return;
// 把登录的用户名和输入框内容全部发送给服务器,让服务器做一次广播,才能同步用户信息。
//把自己名字传给服务器,其实也不用,我在那局部变量保存了
socket.emit("message", net_name, role, uid, icon, inpval: cxt.value );
//数据库添加数据
ajax(
"http://localhost:8849/add",
`net_name=$net_name&icon=$icon&role=$role&content=$cxt.value&uid=$uid`
).then(function(response)
console.log(response);
);
return false;
;
//监听服务器的广播消息,同步用户信息,msg就是点击发送按钮发送的用户信息
socket.on("message", function(msg)
//在这可以通过名字判断是自己就放右边,别人就放左边
// 每个客户端将用户的消息渲染
var newli = document.createElement("li");
// newli.innerHTML = msg.net_name + "(" + msg.role + ")" + ":" + msg.inpval;
if (msg.uid == uid)
newli.setAttribute("class", "data2");
newli.innerHTML = `
<p>
<span>$msg.net_name($msg.role):</span> $msg.inpval
</p>
<div class="img">
<img
src="http://localhost:8848/$msg.icon"
alt=""
/>
</div>`;
else
newli.setAttribute("class", "data");
newli.innerHTML = `
<div class="img">
<img
src="http://localhost:8848/$msg.icon"
alt=""
/>
</div>
<p>
<span>$msg.net_name($msg.role):</span> $msg.inpval
</p>`;
ul.appendChild(newli);
//滚动到底部
content.scrollTo(
top: content.scrollHeight,
behavior: "smooth",
);
cxt.value = "";
);
// 服务器端监听服务端建立连接发来的信息,用于渲染温馨提示信息,msg是服务器返回广播的用户对象数据
socket.on("loginin", function(msg)
// 生成用户进入房间提示信息标签
let tip = document.createElement("p");
console.log(msg.userList);
tip.innerHTML = msg.des;
// 设置样式
tip.className = "tips&以上是关于简易聊天室代码分享 js+socket.io的主要内容,如果未能解决你的问题,请参考以下文章