zoukankan      html  css  js  c++  java
  • django websocket channels 使用

    学习网址:https://channels.readthedocs.io/en/latest/introduction.html

    1、安装 channels

    pip install channels

    pip install channels_redis

    2、setting同级创建  asgi.py

      

    import os
    
    from channels.auth import AuthMiddlewareStack
    from channels.routing import ProtocolTypeRouter, URLRouter
    from django.core.asgi import get_asgi_application
    import chat.routing
    
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
    
    application = ProtocolTypeRouter({
      "http": get_asgi_application(),
      "websocket": AuthMiddlewareStack(
            URLRouter(
                chat.routing.websocket_urlpatterns  #  子应用路由
            )
        ),
    })

    3、子应用创建 routing

    from django.urls import re_path
    
    from . import consumers
    
    websocket_urlpatterns = [
        re_path(r'ws/chat/(?P<room_name>w+)/$', consumers.ChatConsumer.as_asgi()),
    ]

    4、settings 注册 

    INSTALLED_APPS = [....,channels,]
    # channels_redis 
    ASGI_APPLICATION = 'mysite.asgi.application'
    CHANNEL_LAYERS = {
        'default': {
            'BACKEND': 'channels_redis.core.RedisChannelLayer',
            'CONFIG': {
                "hosts": [('127.0.0.1', 6379)],
            },
        },
    }
    # channels
    ASGI_APPLICATION = 'mysite.asgi.application'
    5、 子应用创建  consumers.py 文件
    import json
    from channels.generic.websocket import WebsocketConsumer
    
    class ChatConsumer(WebsocketConsumer):
        def connect(self):
            self.accept()
    
        def disconnect(self, close_code):
            pass
    
        def receive(self, text_data):  #  回复
            text_data_json = json.loads(text_data)
            message = text_data_json['message']
    
            self.send(text_data=json.dumps({
                'message': message
            }))

    6、前端js语法

    const  chatwebsocket = new WebSocket("ws://127.0.0.1:8000")
    chatwebsocket.onmessage = function(e){
    // 后端返回前端消息 执行
    }
    chatwebsocket.onopen = function(e){
    // 连接 时执行
    chatwebsocket.send(JSON.stringify({'内容'}))
    } 
    chatwebsocket.onerror = function(e){
    //  连接 错误时执行
    }
    chatwebsocket.onclose = function(e){
    //连接关闭时执行
    }
    consumers
  • 相关阅读:
    hotmail 收不到邮件的问题
    getaddrinfo 报错 Invalid value for ai_flags
    Avoiding Common Networking Mistakes
    关掉标准输出
    不需要 root 权限的 ping
    select 的问题
    Behavior Tree 用 Lua 实现一个最简行为树
    对 UDP 的一些思考
    Windows UDP sockets: recvfrom() fails with error 10054
    和等于某个数的所有组合
  • 原文地址:https://www.cnblogs.com/ZT-GJ/p/14357920.html
Copyright © 2011-2022 走看看