1:HTML:
在线客服系统{% comment %} 热键 {% endcomment %}
发送 message
关闭连接
var name = '{{username}}';
// 发送到连接上去的后台
var socket = new WebSocket("ws://" + window.location.host + "/websocket/" + name);
//发送数据到服务端
socket.onopen = function () {
alert("您已经连接上客服")
};
// 发送按钮点击
$('#send_message').click(function () {
$('#messagecontainer').prepend('
' + $('#message').val() + '
');if (!socket) {
alert("请重新连接")
} else {
socket.send($('#message').val());
}
});
// 打印服务端返回的数据 接收消息
socket.onmessage = function (e) {
$('#messagecontainer').prepend('
' + e.data + '
');};
// 错误时
socket.onerror = function (event) {
console.log(" websocket.onerror ");
};
// 断开连接时
$("#close").click(function () {
if (socket) {
socket.send("quit");
alert("已断开连接,客服将收不到您发送的信息")
socket.close()
}
});
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
socket.close();
}
// 发送热键设置
function inpuKeyDown(event) {
// console.log(event)
if (event.keyCode == 13) {
// 发送消息
socket.send($('#message').val());
}
}
// 心跳包
setInterval(() => {
socket.send('Hear_t#Beat');
}, 60000)