zoukankan      html  css  js  c++  java
  • 基于长轮询简易版聊天室

    一. 浏览器端代码

    <!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>
    View Code

    二. 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)
    View Code

    此处省略路由配置...

  • 相关阅读:
    [JSOI2009] 游戏
    CF1148H Holy Diver
    [提高组集训2021] 模拟赛3
    CF1458F Range Diameter Sum
    [游记] CSP2021
    CF1396E Distance Matching
    CF1396D Rainbow Rectangles
    【LeetCode】1. 两数之和
    【随笔】开通博客园过程
    MyISAM与InnoDB的区别是什么?
  • 原文地址:https://www.cnblogs.com/guniang/p/12123242.html
Copyright © 2011-2022 走看看