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
相关推荐
万少31 分钟前
AtomCode开发微信小程序《谁去呀》 全流程
前端·javascript·后端
GetcharZp32 分钟前
Epic、暴雪都在用的 C++ 界面利器:Dear ImGui 零基础全景指南
后端
某人辛木1 小时前
Web自动化测试
前端·python·pycharm·pytest
C+++Python1 小时前
详细介绍一下Java泛型的通配符
java·windows·python
pixcarp2 小时前
知识库系统的内容资产闭环怎么设计
服务器·数据库·后端·golang
红尘散仙2 小时前
别再手动录屏了:用 VHS 给终端应用生成会动的文档素材
后端·rust
小帅热爱难回头2 小时前
编写Skill生成AI落地项目系统架构
python
diving deep3 小时前
脚本速览-python
开发语言·python
2601_951643774 小时前
Python第一,Java跌出前三,C语言杀回来了
java·c语言·python·编程语言排行·技术趋势
张忠琳5 小时前
【Go 1.26.4】Golang Select 深度解析
开发语言·后端·golang