Django+channels -> websocket

Django+channels -> websocket

学习视频: https://www.bilibili.com/video/BV1J44y1p7NX/?p=10
学习记录截图: https://blog.csdn.net/qq_22038327/article/details/128586353

workon # 查看虚拟环境
mkvirtualenv web -p python3.10 # 创建虚拟环境
workon web # 进入虚拟环境

pip install django==4.1.5
pip install channels==4.0.0
pip install daphne==4.0.0

pip install black==22.12.0 # format code
django-admin startproject ws_demo
cd ws_demo
python manage.py startapp app01
ws_demo.setings.py
# 注册channels
INSTALLED_APPS = [
    'daphne', # 放在 top 的位置
    'channels',
    'django.contrib.admin',
    ...
]

TEMPLATE = BASE_DIR.joinpath('app01/template')
TEMPLATES = [
    {...
        'DIRS': [TEMPLATE],
    }...
]

# WSGI_APPLICATION = 'ws_demo.wsgi.application'
# 添加 ASGI_APPLICATION
ASGI_APPLICATION = 'ws_demo.asgi.application'

启动server

python manage.py migrate
python manage.py runserver


在这里插入图片描述

http 相关的py内容

app01.views.py
from django.shortcuts import render
def index(requests):
    return render(requests, 'index.html')
ws_demo.urls.py
from app01.views import index
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
]
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Title</title>
        <style>
            .msg{
                height: 100%;
                width: 50%;
                border: 1px solid #dddddd;
            }
        </style>
    </head>
    <body>
        <div class="msg", id="msg"></div>
        <div>
            <input type="text" placeholder="input" id="txt">
            <input type="button" value="send">
        </div>
    </body>
</html>

在这里插入图片描述


websocket 相关的py内容

app01.consumers.py (相当于views)
import sys
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer


class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        print(sys._getframe().f_code.co_name)
        self.accept()
        # return super().websocket_connect(message)

    def websocket_receive(self, message):
        print(sys._getframe().f_code.co_name)
        msg = message['text']
        if msg == 'close':
            self.close()
            return

        msg_server = f'{msg} servered...'
        self.send(msg_server)
        return super().websocket_receive(message)

    def websocket_disconnect(self, message):
        print(sys._getframe().f_code.co_name)
        raise StopConsumer()
        return super().websocket_disconnect(message)
app01.routings.py (相当于urls)
from django.urls import re_path
from .consumers import ChatConsumer
websocket_urlpatterns = [
    re_path(r'ws/(?P<group>\w+)/$', ChatConsumer.as_asgi())
]
ws_demo.asgi.py
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from app01.routings import websocket_urlpatterns

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ws_demo.settings')

# application = get_asgi_application()
application = ProtocolTypeRouter(
    {
        'http': get_asgi_application(),
        'websocket': URLRouter(websocket_urlpatterns),
    }
)
postman 测试 websocket 接口

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在浏览器中实现http+websocket

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Title</title>
        <style>
            .msg{
                height: 100%;
                width: 50%;
                border: 1px solid #dddddd;
            }
        </style>
    </head>
    <body>
        <div class="msg", id="msg"></div>
        <div>
            <input type="text" placeholder="input" id="txt">
            <input type="button" value="send" onclick="sendMsg()">
            <input type="button" value="close" onclick="closeCon()">
        </div>
    </body>
    <script>
        function txtShow(content){
            var tag = document.createElement("div")
            tag.innerText = content
            document.getElementById("msg").append(tag)
        }
        
        socket = new WebSocket("ws://127.0.0.1:8000/ws/room/")
        socket.onopen = function(event){
            txtShow('[onOpen]')
        }
        socket.onmessage = function(event){
            txtShow(event.data)
        }
        socket.onclose = function(event){
            txtShow('[onClose]')
        }

        function sendMsg(){
            var tag = document.getElementById("txt")
            txtShow(tag.value)
            socket.send(tag.value)
        }
        function closeCon(){
            txtShow('close')
            socket.send('close')
        }
    </script>
</html>

最终效果

在这里插入图片描述


群聊

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 Django-channels 实现 WebSocket 的示例: 首先,安装 Django-channels: ``` pip install channels ``` 然后,在 Django 的 settings.py 中添加以下配置: ```python INSTALLED_APPS = [ ... 'channels', ] ASGI_APPLICATION = 'myproject.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } ``` 在 myproject 目录下创建一个 routing.py 文件,添加以下内容: ```python from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from myapp.consumers import MyConsumer application = ProtocolTypeRouter({ 'websocket': URLRouter([ path('ws/', MyConsumer.as_asgi()), ]), }) ``` 在 myapp 目录下创建一个 consumers.py 文件,添加以下内容: ```python from channels.generic.websocket import AsyncWebsocketConsumer import json class MyConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.send(text_data=json.dumps({ 'message': message })) ``` 在你的模板中添加以下 JavaScript 代码,用于连接 WebSocket 和发送消息: ```javascript const socket = new WebSocket('ws://' + window.location.host + '/ws/'); socket.onmessage = function(e) { const data = JSON.parse(e.data); console.log(data); }; socket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.querySelector('#chat-message-submit').click(); } }; document.querySelector('#chat-message-submit').onclick = function(e) { const messageInputDom = document.querySelector('#chat-message-input'); const message = messageInputDom.value; socket.send(JSON.stringify({ 'message': message })); messageInputDom.value = ''; }; ``` 最后,启动 Django 服务器,打开浏览器访问你的应用程序,进入调试器,打开控制台,你应该可以看到从服务器发送的消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值