长轮询

长轮询

# 轮询,在前端通过写js实现。缺点:有延迟、服务器压力大。


```
首先需要为每个用户维护一个队列,用户浏览器会通过js递归向后端自己的队列获取数据,自己队列没有数据,会将请求夯住(去队列中获取数据),夯一段时间之后再返回。
注意:一旦有数据立即获取,获取到数据之后会再发送请求。
```

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
	url(r'^admin/', admin.site.urls),
	url(r'^index/$',views.index),
	url(r'^send/msg/$',views.send_msg),
	url(r'^get/msg/$',views.get_msg),
]

views.py

from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
import queue

QUEUE_DICT = {}

def index(request):
	username = request.GET.get('username')
	if not username:
		return HttpResponse('请输入名字')
	QUEUE_DICT[username] = queue.Queue()
	return render(request,'index.html',{'username':username})

def send_msg(request):
	"""
	接受用户发来的消息
	:param request:
	:return:
	"""
	text = request.POST.get('text')
	for k,v in QUEUE_DICT.items():
		v.put(text)
	return HttpResponse('ok')

def get_msg(request):
	"""
	想要来获取消息
	:param request:
	:return:
	"""
	ret = {'status':True,'data':None}

	username = request.GET.get('user')
	user_queue = QUEUE_DICT.get(username)

	try:
		message = user_queue.get(timeout=10)
		ret['data'] = message
	except queue.Empty:
		ret['status'] = False
	return JsonResponse(ret)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>
	<h1>聊天室({{ username }})</h1>
	<div class="form">
		<input id="txt" type="text" placeholder="请输入文字">
		<input id="btn" type="button" value="发送">
	</div>
	<div id="content">

	</div>

	<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
	<script>

		$(function () {
			$('#btn').click(function () {
				var text = $("#txt").val();
				$.ajax({
					url:'/send/msg/',
					type:'POST',
					data: {text:text},
					success:function (arg) {
						console.log(arg);
					}
				})
			 });

			getMessage();
		});

		function getMessage() {
			$.ajax({
				url:'/get/msg/',
				type:'GET',
				data:{user:"{{ username }}" },
				dataType:"JSON",
				success:function (info) {
					console.log(info);
					if(info.status){
						var tag = document.createElement('div');
						tag.innerHTML = info.data;
						$('#content').append(tag);
					}
					getMessage();
				}
			})
		}
	</script>
</body>
</html>
posted @ 2019-11-29 15:05  阿浪阿浪  阅读(305)  评论(0编辑  收藏  举报