Django使用WebSocket

django channels 是django支持websocket的一个模块。

1安装.

|-------------------------|
| pip3 install channels |

2.在settings中添加配置

python 复制代码
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'channels',
]

ASGI_APPLICATION = "django_channels_demo.routing.application"

3.创建websocket应用和路由

python 复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from chat import consumers


application = ProtocolTypeRouter({
    'websocket': URLRouter([
        url(r'^chat/$', consumers.ChatConsumer),
    ])
})

4.编写处理websocket逻辑业务

python 复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

class ChatConsumer(WebsocketConsumer):

    def websocket_connect(self, message):
        self.accept()

    def websocket_receive(self, message):
        print('接收到消息', message)
        self.send(text_data='收到了')

    def websocket_disconnect(self, message):
        print('客户端断开连接了')
        raise StopConsumer()

5.启动:

python 复制代码
daphne -b 0.0.0.0 -p xxxx xxxx.asgi:application
相关推荐
伤心的梧桐叶26 分钟前
Picset与创客贴比等待时间,没做完的任务不能从表里消失
python
大哥430929 分钟前
on-failure 不扛重启:一次 Docker restart 策略的反直觉排查
后端
房西杭42 分钟前
GM指令:仓库扩容、清空仓库(行会仓库 + 个人仓库,Lua + proto + GMMgr注册)
后端
大哥430942 分钟前
不报错 ≠ 生效:三类"静默失效"缺陷与它们的共同指纹
后端
没有气的汽水42 分钟前
一次 SQS 消费者静默退出的排查:问题最后竟然出在日志里
python
房西杭44 分钟前
整理背包 SortBag 完整实现逻辑
后端
用户4500301402344 分钟前
物业催缴系统为什么总在"冷却"这一步翻车:账期建模与规则命中的几个取舍
python
Marcus学原理1 小时前
Playwright 入门:让浏览器自动完成重复操作
后端
弦儿1 小时前
后端 Web 实战:部门管理模块全流程(前后端分离 + RESTful + 三层架构 + 日志)
后端·restful
房西杭1 小时前
背包<->仓库转移接口(BagMgr + StoreMgr,Lua)
后端