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
相关推荐
於時光清歌5 分钟前
Git基础使用
后端
明月_清风22 分钟前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
风象南22 分钟前
纯文本模型竟然也能直接“画图”,而且还很好用
前端·人工智能·后端
明月_清风25 分钟前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
IT_陈寒40 分钟前
Vite vs Webpack:5个让你的开发效率翻倍的实战对比
前端·人工智能·后端
JaguarJack1 小时前
FrankenPHP 原生支持 Windows 了
后端·php·服务端
BingoGo1 小时前
FrankenPHP 原生支持 Windows 了
后端·php
Moment13 小时前
Vibe Coding 时代,到底该选什么样的工具来提升效率❓❓❓
前端·后端·github
Victor35614 小时前
MongoDB(27)什么是文本索引?
后端
可夫小子14 小时前
OpenClaw基础-3-telegram机器人配置与加入群聊
后端