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
相关推荐
技术小泽1 分钟前
OptaPlanner入门以及实战教学
后端·面试·性能优化
JavaGuide1 分钟前
利用元旦假期,我开源了一个大模型智能面试平台+知识库!
前端·后端
5:001 小时前
Python进阶语法
开发语言·python
橙子家1 小时前
Serilog 日志库简单实践(四)消息队列 Sinks(.net8)
后端
Victor3561 小时前
Hibernate(21)Hibernate的映射文件是什么?
后端
pe7er1 小时前
如何阅读英文文档
java·前端·后端
pe7er1 小时前
IDEA 实用小技巧(自用)
后端
Victor3561 小时前
Hibernate(22)Hibernate的注解配置是什么?
后端
喵叔哟2 小时前
15.故障排查与调试
后端·docker·容器·服务发现
小康小小涵2 小时前
睿抗机器人大赛魔力元宝
python·ubuntu·gitee·github