长轮询
即前端每隔一段时间就发送一次请求。当服务端接收请求的时候,我们先查询是否有前端想要的数据,如果有则返回,如果没有,则先将请求hang住一段时间,比如30s,如果这30s内。服务端有客户端想要的数据了,则直接返回。如果30s还没有返回,则给前端返回空。前端接收后,立刻发另一个请求,以此往复。一般基于队列来实现长轮询
前端代码
<html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script> <style> .msg{ height: 500px; border: 1px solid #ddd; width: 100%; } </style> </head> <body> <div class="msg"></div> <div> <input type="text" placeholder="请输入" id="text"> <input type="button" value="发送" onclick="sendMsg();"> </div> </body> <script> var USER_ID = "{{ uid }}"; function sendMsg() { var text = $("#text").val(); console.log(text) $.ajax( { url:'/send/msg/', type:'GET', data:{ text:text },success:function (res) { console.log('请求发送成功',res) } } ) } function getMsg(){ $.ajax({ url:'/get/msg/', type:'GET', data:{ uid: 'lwj', //此处写死,应该要写每个用户uid值 }, dataType:"JSON", success:function (res) { if (res.status){ //如果存在则说明有数据 var tag = $("<div>"); tag.text(res.data); //创建一个标签<div></div> $(".msg").append(tag); //将标签添加到页面 console.log(USER_ID) } getMsg(); } }) } $(function(){ getMsg(); //页面加载就开始调用函数getMsg() }) </script> </html>
后端实现
from django.shortcuts import render,HttpResponse from django.views import View from django.http import JsonResponse import queue # Create your views here. USER_QUEUE = { } class home(View): def get(self,request,*args,**kwargs): uid = request.GET.get('uid') USER_QUEUE[uid] = queue.Queue() #为每个用户创建一个队列 return render(request,'index.html') class sendMsg(View): def get(self,request,*args,**kwargs): text = request.GET.get('text') for uid, q in USER_QUEUE.items(): q.put(text) #将接收到的数据,存放到每个用户的每个队列 return HttpResponse('发送成功') class getMsg(View): def get(self,request,*args,**kwargs): uid = request.GET.get('uid') q = USER_QUEUE[uid] res = {'status':True,'data':None} try: data = q.get(timeout=10) #获取相应用户的队列的值,如果改队列超过10s没有值,则抛出异常 res['data'] = data #如果有值,则赋值 except queue.Empty as e: #如果超过10s,队列里还没数据,就报异常 res['status'] = False return JsonResponse(res)
标签:uid,get,text,轮询,request,res,data From: https://www.cnblogs.com/powfu/p/16898018.html