django websocket 配置 channels

http协议websocket协议
  • http协议,一次请求一次响应。

  • websocket 协议,创建持久的连接不断开,基于这个连接可以进行手法数据(服务器可以主动像客户端发送数据)

    • web聊天室

    • 实时图标,柱状图,饼图。

websocket 原理
  • 连接,客户端发起

  • 握手验证,客户端发送消息,后端接收到消息在做一些特殊处理并且返回

    • 客户端发送随机字符串

    • 服务端接收,加上magic string 拼接,进行hmac1加密,在base64编码返回给前端

    • 前端接收加密的密文,进行验证。

  • 收发数据

    • 先获取第二个字节 8 位 10001010

    • 再获取第二个字节的后七位 0001010

      • =127 , 2个字节,8个字节, 其他字节(4个字节masking key + 数据)

      • =126, 2个字节,2个字节 其他字节(4个字节masking key + 数据)

      • 《=125 ,2字节 其他字节(4个字节masking key + 数据)

      • 获取masking key 然后对数据进行解密。

  • 断开连接

django框架

djano默认不支持websocket ,需要安装组件

pip install channels

配置

1.注册app

注意事项

  • django == 4.2.7

  • channels == 4.0.0

  • 此版本需要注册app的时候将 daphne 放到最前面否则不能以asgi 的方式启动服务

INSTALLED_APPS = [
    'daphne',
    'channels',
]
2.在setting 中添加 ASGI_APPLICATION = ‘websocket.asgi.application’
ASGI_APPLICATION = 'websocket.asgi.application'
3.修改asgi 文件
import os

from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from . import routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket.settings')

#application = get_asgi_application()

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": URLRouter(routing.websocket_urlpatterns)
})
4.setting 文件同级目录创建 routing 文件
from django.urls import  re_path

from app01 import consumers

websocket_urlpatterns = [
    re_path(r'ws/(?P<group>\w+)/$', consumers.ChatConsumer.as_asgi()),
]
5.app01目录下创建consumers.py , 编写处理websocket 业务逻辑
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer


def websocket_receive(self, message):
    # 浏览器基于websocket向后端发送数据,自动触发接收消息。
    print(message)
    self.send("不要回复不要回复")
    # self.close()


def websocket_disconnect(self, message):
    # 客户端与服务端断开连接时,自动触发。
    print("断开连接")
    raise StopConsumer()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值