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
相关推荐
wuyk55512 分钟前
Spider-第14讲-表单提交与CSRF
前端·爬虫·python·elasticsearch·csrf
Csvn33 分钟前
Nginx 反向代理入门:proxy_pass 两种形态、超时链与 502/504 分辨
后端·nginx
汤姆宝库41 分钟前
RoPE旋转位置编码的实现与长上下文外推
python·深度学习·机器学习
LVZ1 小时前
AI Agent 缺的不是更强的模型,而是一个运行时
前端·javascript·后端
用户019027581611 小时前
股票代码格式对照:各数据源代码转 AlphaFeed
python
鶴哥只手遮天1 小时前
《VulkanSceneGraph 1.1.16 源码深度解析》第二章 内存工程:Allocator、MemoryBlock 与场景图的物理布局
后端
im_AMBER1 小时前
IO 多路复用:select、poll 和 epoll
后端·面试·架构
码农Kzx1 小时前
【开源】当桌面图标开始打台球:我用 WinForms 做了一桌“真的”台球
后端
鶴哥只手遮天1 小时前
《VulkanSceneGraph 1.1.16 源码深度解析》第五章 数据对象:从 `Data` 到 `VkBuffer`/`VkImage` 的完整链路
后端
__underline__2 小时前
冷门Python知识点005篇:list.sort( )的排序稳定性,是用0字节额外内存实现的
python·算法