基于长轮询简易版聊天室
一. 浏览器端代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>web 聊天室 {{ name }}</h3> <div> <input id="txt" type="text" placeholder="请输入消息"> <input type="button" value="发送" id="btn"> </div> <div> <h3>聊天记录</h3> <div id="content"></div> </div> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script> $(function () { $("#btn").click(function () { $.ajax({ url:'/send_msg/', type: 'POST', data:{'msg': $("#txt").val()}, success: function (arg) { tag = $('<p>'); tag.text(arg); $("#content").append(tag); } }) }) }); function getMessage() { $.ajax({ url:'/get_msg/', type:'get', dataType:'JSON', data:{"name":"{{name}}"}, success: function (arg) { console.log(arg); if (arg["msg"]) { tag = $('<p>'); tag.text(arg["msg"]); $("#content").append(tag); } else { console.log("没有新消息!") } getMessage() } }) } $(function () { getMessage() }) </script> </body> </html>
二. django后端代码
from django.shortcuts import render,HttpResponse from django.http import JsonResponse import queue QUEUE_DICT = {} def home(request): name = request.GET.get('name') QUEUE_DICT[name] = queue.Queue() return render(request,'home.html',{"name":name}) def send_msg(request): msg = request.POST.get("msg") print(msg) for q in QUEUE_DICT.values(): q.put(msg) return HttpResponse("消息发送成功") def get_msg(request): info = {"status":True,"msg":None} name = request.GET.get("name") q = QUEUE_DICT[name] try: msg = q.get(timeout=10) info["msg"] = msg except queue.Empty as e: info["status"] = False return JsonResponse(info)
此处省略路由配置...
We are down, but not beaten. tested but not defeated.