目录
1.运用场景(实现效果):
2.代码及其讲解:
js配置:
(1)时间判断函数:
(2)建立ws连接:
结束!
1.运用场景(实现效果):
前端运用原生js来与后端提供的ws进行交互,实现在线实时聊天,离线储存数据方便读取聊天记录的效果,效果图如下:文章来源:https://www.toymoban.com/news/detail-519189.html
文章来源地址https://www.toymoban.com/news/detail-519189.html
2.代码及其讲解:
js配置:
(1)时间判断函数:
function getTime() {
var result = 0;
var time = new Date();
var h = time.getHours();
h = h < 10 ? '0' + h : h;
var m = time.getMinutes();
m = m < 10 ? '0' + m : m;
var s = time.getSeconds();
s = s < 10 ? '0' + s : s;
var year = time.getFullYear();
var month = time.getMonth() + 1;
month = month < 10 ? '0' + month : month;
var dates = time.getDate();
var result = year + '-' + month + '-' + dates + ' ' + h + ':' + m + ':' + s;
return result;
}//获取当前时间
function getprTime() {
let chattime = document.getElementsByClassName('chattime');
chattime = chattime[chattime.length - 1].innerHTML;
return chattime
}//获取的最后一个时间框的时间
function getfirstTime() {
let chattime = document.getElementsByClassName('chattime');
chattime = chattime[0].innerHTML;
return chattime
}//获取的最后第一个时间框的时间
function recontrasttime(time, nowtime) {
let data = new Date(time.replace(/-/g, "/"));
let t1 = new Date(nowtime.replace(/-/g, "/"));
let times = t1.getTime() - data.getTime();
let days = parseInt(times / (24 * 1000 * 3600));
if (days > 0) {
return false;
}
let leave = times % (24 * 3600 * 1000);
let h = parseInt(leave / (3600 * 1000));
if (h > 0) {
return false;
}
let h_leave = leave % (3600 * 1000);
let min = parseInt(h_leave / (60 * 1000));
if (min == 1 || min == 0) {
return true;
} else {
return false;
}
}//比较以前和现在两者的时间,来判断是否添加时间框
(2)建立ws连接:
var websocket = null;
var creatws= function (userid) {
if ('WebSocket' in window) {
//用于创建WebSocket对象,webSocketTest对应的是java类的注解值
websocket = new WebSocket(`ws://152.136.99.236:8080/websocket/${userid}`);
} else {
hintFn("wrong","当前浏览器不支持")
}
//连接发生错误的时候回调方法;
websocket.onerror = function () {
hintFn("warning","连接错误")
// alert("连接错误");
}
//连接成功时建立回调方法
websocket.onopen = function () {
//WebSocket已连接上,使用send()方法发送数据
hintFn("success","连接成功")
// alert("连接成功");
};
// 收到消息的回调方法
websocket.onmessage = function (msg) {
let data = JSON.parse(msg.data)
console.log(msg.data);
console.log(data);
if (data.users != undefined) {
for (let i of data.users) {
if (i.userId == toid) {
useronline[0].style.display = 'block'
useronline[1].style.display = 'none'
}
}
return
} else {
if (!recontrasttime(getprTime(), getTime())) {
messagebody.innerHTML += `
<div class="amessage">
<div class="chattimebox"><span class="chattime">${getTime()}</span></div>
<div class="chat otherchat">
<img src="${userimg}" alt="">
<div class="chattext">${data.text}</div>
</div>
</div>
`
} else {
messagebody.innerHTML += `
<div class="amessage">
<div class="chat otherchat">
<img src="${userimg}" alt="">
<div class="chattext">${data.text}</div>
</div>
</div>
`
}//渲染数据
if(nowpage==1){
messagebody.scrollTop = messagebody.scrollHeight;
}
}
};
//连接关闭的回调方法
websocket.onclose = function () {
closed();
isFinite('warning',"连接已关闭")
// alert("关闭成功");
};
function closed() {
websocket.close();
sFinite('warning',"连接已关闭")
// alert("点击关闭");
}
sendchat.onclick=function(){
if(isnull(judgeStrs(chattext.value))){
hintFn('warning', "请输入你要输入的内容")
return
}
let newob = {
to: toid,
from: fromid,
text: judgeStrs(chattext.value),
}
if (!recontrasttime(getprTime(), getTime())) {
messagebody.innerHTML += `
<div class="amessage">
<div class="chattimebox"><span class="chattime">${getTime()}</span></div>
<div class="chat mychat">
<img src="${myimg}" alt="">
<div class="chattext">${chattext.value}</div>
</div>
</div>
`
} else {
messagebody.innerHTML += `
<div class="amessage">
<div class="chat mychat">
<img src="${myimg}" alt="">
<div class="chattext">${chattext.value}</div>
</div>
</div>
`
}
websocket.send(JSON.stringify(newob)); //给后台发送数据
messagebody.scrollTop = messagebody.scrollHeight;
chattext.value=``
}
结束!
到了这里,关于js和java交互websocket实现实时聊天的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!