1:HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>在线客服系统</title>
</head>
<body>
{% comment %} 热键 {% endcomment %}
<input type="text" id="message" value="" onkeydown="inpuKeyDown(event)"/>
<button type="button" id="send_message">发送 message</button>
<button type="button" id="close">关闭连接</button>
<div id="messagecontainer"></div>
</body>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var name = ‘{{username}}‘;
// 发送到连接上去的后台
var socket = new WebSocket("ws://" + window.location.host + "/websocket/" + name);
//发送数据到服务端
socket.onopen = function () {
alert("您已经连接上客服")
};
// 发送按钮点击
$(‘#send_message‘).click(function () {
$(‘#messagecontainer‘).prepend(‘<p>‘ + $(‘#message‘).val() + ‘</p>‘);
if (!socket) {
alert("请重新连接")
} else {
socket.send($(‘#message‘).val());
}
});
// 打印服务端返回的数据 接收消息
socket.onmessage = function (e) {
$(‘#messagecontainer‘).prepend(‘<p>‘ + e.data + ‘</p>‘);
};
// 错误时
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)
</script>
</html>
配置:
1:url.py urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(‘websocket_client/(?P<username>\w+)‘, view.websocket_client), url(‘websocket/(?P<username>\w+)‘, view.websocket), ] 2:settings.py INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, "dwebsocket", ] EBSOCKET_ACCEPT_ALL=True # 可以允许每一个单独的视图实用websockets
3:view.py:
"""
1 心跳包问题:定时发送标识到后端,返回一个标识,前端叠加变量,超过3次就断开连接
2 一对一指定用户聊天:使用数据库记录两个ID对应的聊天记录,用户访问sockt网页后取出数据发送到聊天框
3 聊天室 将所有用户发送的消息,储存在redis或者session里面,每个用户访问网页后将全部信息遍历发送到对方的聊天框
"""
import json
import time
from dwebsocket.decorators import accept_websocket
from django.shortcuts import render,HttpResponse
# Create your views here.
def websocket_client(request, username):
return render(request,‘index.html‘,{‘username‘: username})
# 存储连接websocket的用户
clients = []
@accept_websocket
def websocket(request, username):
try:
if request.is_websocket():
print("request",request)
print("当前用户",username)
# 是否是第一次连接
if username not in clients:
# 设置发送数据为json格式 回复对应的用户
request.websocket.send(json.dumps({"first":"您好,很高兴为您服务,请简单简述您需要提问的问题{}".format(time.strftime(‘%Y.%m.%d %H:%M:%S‘, time.localtime(time.time())))}, ensure_ascii=False).encode("utf-8"))
# 添加用户到已经存在用户
clients.append(username)
else:
request.websocket.send(json.dumps({"User":"欢迎回来~"}, ensure_ascii=False).encode("utf-8"))
print("当前咨询所有用户",clients)
# 设置发送至前端的次数
while True:
# for message in request.websocket:
message = request.websocket.wait()
if not message:
break
else:
str_message = str(message, ‘utf-8‘)
print(‘message‘,str_message)
# 如果收到是心跳标志 就加1
if str_message == "Hear_t#Beat":
heart = heart + 1
if str_message == ‘quit‘:
print("quit里面")
clients.remove(username)
request.websocket.close() # 关闭服务
break
# 添加到数据库 redis
# 取到两个用户的数据发送给前台
# 设置发送前端的数据
messages = {
‘time‘: time.strftime(‘%Y.%m.%d %H:%M:%S‘, time.localtime(time.time())),
‘msg‘: str_message,
}
# 设置发送数据为json格式 回复对应的用户
request.websocket.send(json.dumps(messages,ensure_ascii=False).encode("utf-8"))
except:
pass