• django使用websocket


        WebSocket协议是基于TCP的一种新的协议。WebSocket最初在HTML5规范中被引用为TCP连接,作为基于TCP的套接字API的占位符。它实现了浏览器与服务器全双工(full-duplex)通信。其本质是保持TCP连接,在浏览器和服务端通过Socket进行通信

    django 使用websocket需要安装channels

    pip3 install channels==2.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
    创建django项目

      在settings.py里注册channels

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'app01.apps.App01Config',
        # 项目中要使用channels做websocket了.
        "channels",
    ]

      本质: channels会把原来只支持http协议的wsgi,换成支持http和websocket协议的asgi

    配置application

    # settings.py 
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'app01.apps.App01Config',
        # 项目中要使用channels做websocket了.
        "channels",
    ]
    
    ASGI_APPLICATION = "channel_demo.routing.application"
    # channel_demo/routing.py(新建routing.py文件)
    from channels.routing import ProtocolTypeRouter, URLRouter
    from django.conf.urls import url
    from app01 import consumers
    application = ProtocolTypeRouter({
    'websocket': URLRouter([
    url(r'^chat/$', consumers.ChatConsumer),
    ])
    })

    app下建立consumers文件

    和view文件功能一样,专门处理websocket请求
    from channels.generic.websocket import WebsocketConsumer
    from channels.exceptions import StopConsumer
    
    CONSUMER_OBJECT_LIST = []
    
    class ChatConsumer(WebsocketConsumer):
    
        def websocket_connect(self, message):
            """
            客户端发来连接请求之后就会被触发
            :param message:
            :return:
            """
            # 服务端接收连接,向客户端浏览器发送一个加密字符串
            self.accept()
            # 连接成功
            CONSUMER_OBJECT_LIST.append(self)
    
        def websocket_receive(self, message):
            """
            客户端浏览器向服务端发送消息,此方法自动触发
            :param message:
            :return:
            """
            # 服务端给客户端回一条消息
            # self.send(text_data=message['text'])
            for obj in CONSUMER_OBJECT_LIST:
                obj.send(text_data=message['text'])
        def websocket_disconnect(self, message):
            """
            客户端主动断开连接
            :param message:
            :return:
            """
            # 服务端断开连接
            CONSUMER_OBJECT_LIST.remove(self)
            raise StopConsumer()

    web聊天室HTML样例,用ajax实现

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>欢迎进入Channels聊天室</h1>
        <div>
            <input type="text" id="txt" placeholder="请输入">
            <input type="button" onclick="sendMsg();" value="发送">
            <input type="button" onclick="close();" value="断开连接">
        </div>
        <div>
            <h3>聊天记录</h3>
            <div id="content"></div>
        </div>
    
        <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
        <script>
            var ws = new WebSocket("ws://127.0.0.1:8000/chat/");
    
            ws.onopen = function(){
                //客户端在握手环节验证成功之后,自动执行此方法.
                console.log('连接成功');
            };
    
            ws.onmessage = function (event) {
                var tag = $('<div>');
                tag.text(event.data);
                $('#content').append(tag);
            };
    
            function sendMsg() {
                ws.send($('#txt').val());
            }
            
            function close() {
                ws.close();
            }
        </script>
    </body>
    </html>
  • 相关阅读:
    整理
    C# =>语法
    这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”解决办法
    腾讯云静态资源放到cos存储桶里,并开启CDN自定义域名加速
    react lodash节流this找不到正确用法
    reactrouter V6踩坑
    查询net Framework 安装版本
    Nginx实现同一个端口访问不同前后端项目
    vue3 + vite + ts 学习笔记
    Vue3 全家桶,从 0 到 1 实战项目
  • 原文地址:https://www.cnblogs.com/zhanghan5/p/12118359.html
Copyright © 2020-2023  润新知