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
相关推荐
hrrrrb1 小时前
【Spring Boot 快速入门】八、登录认证(一)基础登录与认证校验
spring boot·后端
王大锤·2 小时前
基于spring boot的个人博客系统
java·spring boot·后端
bobz9652 小时前
QT designer 常用技巧
后端
shi57832 小时前
C# 常用的线程同步方式
开发语言·后端·c#
码农派大星。3 小时前
Selenium在Pyhton应用
python·selenium·测试工具
没逻辑3 小时前
抗量子密码技术(PQC)演变
后端·量子计算
day>day>up3 小时前
django uwsgi启动报错failed to get the Python codec of the filesystem encoding
后端·python·django
Livingbody3 小时前
FastMCP In Action跑通第一个MCP之跟学python版
后端
Shun_Tianyou4 小时前
Python Day25 进程与网络编程
开发语言·网络·数据结构·python·算法
bobz9654 小时前
QT 中的三种基本UI类型:Main Window | Widget | Dialog
后端