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
相关推荐
嘻哈baby12 分钟前
Go context详解:超时控制与请求链路追踪
后端
津津有味道25 分钟前
Python写入URI网址到Ntag 424 DNA标签配置开启动态UID计数器镜像
linux·python·nfc·动态uid·424·cma加密数据
计算机学姐30 分钟前
基于SpringBoot的智能家教服务平台【2026最新】
java·spring boot·后端·mysql·spring·java-ee·intellij-idea
思成Codes34 分钟前
Go 语言中数组与切片的本质区别
开发语言·后端·golang
superman超哥1 小时前
Rust Trait约束(Trait Bounds):类型能力的精确契约
开发语言·后端·rust·rust trait约束·trait bounds·类型能力·精确契约
superman超哥1 小时前
Rust Where子句的语法:复杂约束的优雅表达
开发语言·后端·rust·rust where子句·复杂约束·优雅表达
2401_841495641 小时前
【Python高级编程】Python 核心语法速查演示
python·字符串·集合·列表·元组·字典·运算符
xiaok1 小时前
使用docker部署koa+sql server+react项目完整过程
后端
SadSunset1 小时前
(44)Spring6集成MyBatis3.5(了解即可,大部分用springboot)
java·spring boot·后端
武子康1 小时前
大数据-199 决策树模型详解:节点结构、条件概率视角与香农熵计算
大数据·后端·机器学习