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
相关推荐
ingcc几秒前
gorm时间处理
后端
ingcc2 分钟前
Spring事务简介【重点】
后端
码不停蹄的玄黓3 分钟前
Java 应用 CPU 过高排查全流程
java·开发语言·python
ingcc4 分钟前
SpringAOP简介和作用
后端
许彰午5 分钟前
11_Java集合框架概述
java·windows·python
椒盐土豆5 分钟前
Spring的事务捕捉器一看就懂!
后端
小谢小哥6 分钟前
64-依赖冲突解决详解
java·后端·架构
好好风格7 分钟前
微软这个 14 万星工具,把 PDF、PPT、Excel 都变成大模型爱读的 Markdown
人工智能·python·开源
阿杰AJie9 分钟前
ExcelUtils样式相关工具
java·后端
小糖学代码10 分钟前
机器学习:1.机器学习基本概念
人工智能·python·机器学习