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 小时前
java集成telegram机器人
java·python·机器人·telegram
漫谈网络1 小时前
Telnetlib三种异常处理方案
python·异常处理·telnet·telnetlib
Xudde.2 小时前
加速pip下载:永久解决网络慢问题
网络·python·学习·pip
兆。2 小时前
电子商城后台管理平台-Flask Vue项目开发
前端·vue.js·后端·python·flask
未名编程2 小时前
LeetCode 88. 合并两个有序数组 | Python 最简写法 + 实战注释
python·算法·leetcode
weixin_437398212 小时前
RabbitMQ深入学习
java·分布式·后端·spring·spring cloud·微服务·rabbitmq
魔障阿Q2 小时前
windows使用bat脚本激活conda环境
人工智能·windows·python·深度学习·conda
洋芋爱吃芋头2 小时前
hadoop中的序列化和反序列化(3)
大数据·hadoop·python
零炻大礼包3 小时前
【MCP】服务端搭建(python和uv环境搭建、nodejs安装、pycharma安装)
开发语言·python·uv·mcp
来自星星的坤3 小时前
Python 爬虫基础入门教程(超详细)
开发语言·爬虫·python