在Django5中使用Websocket进行通信

2023-12-30 11:52

本文主要是介绍在Django5中使用Websocket进行通信,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Docker安装Redis

docker run --restart=always -p 6379:6379 --name redis -d redis:7.0.12  --requirepass zhangdapeng520

安装依赖

参考文档:https://channels.readthedocs.io/en/latest/installation.html

pip install "channels[daphne]"

展示聊天页面

新增:chat/templates/chat/index.html

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"/><title>Chat Rooms</title>
</head>
<body>请输入您要进入的房间名称<br><input id="room-name-input" type="text" size="100"><br><input id="room-name-submit" type="button" value="进入房间"><script>// 输入框聚焦document.querySelector('#room-name-input').focus();// 输入框按下enter键,相当于点击提交按钮document.querySelector('#room-name-input').onkeyup = function(e) {if (e.key === 'Enter') {document.querySelector('#room-name-submit').click();}};// 提交按钮点击document.querySelector('#room-name-submit').onclick = function(e) {// 获取房间名称const roomName = document.querySelector('#room-name-input').value;// 重定向到指定房间window.location.pathname = '/chat/' + roomName + '/';};</script>
</body>
</html>

修改:chat/views.py

from django.shortcuts import renderdef index(request):"""首页路由"""return render(request, "chat/index.html")

新增:chat/urls.py

from django.urls import pathfrom . import viewsurlpatterns = [path("", views.index, name="index"),
]

修改:Django5Websocket/urls.py

from django.contrib import admin
from django.urls import include, pathurlpatterns = [path("chat/", include("chat.urls")),path("admin/", admin.site.urls),
]

启动服务,浏览器访问:http://localhost:8000

建立Websocket服务

新增:chat/consumers.py

import jsonfrom channels.generic.websocket import WebsocketConsumerclass ChatConsumer(WebsocketConsumer):"""Websocket通信类"""def connect(self):"""建立连接"""self.accept()def disconnect(self, close_code):"""断开连接"""passdef receive(self, text_data):"""接收消息"""# 转换为JSON类型text_data_json = json.loads(text_data)# 提取消息message = text_data_json["message"]# 重新发送JSON文本消息self.send(text_data=json.dumps({"message": message}))

新增:chat/routing.py

from django.urls import re_pathfrom . import consumerswebsocket_urlpatterns = [# 定义websocket的连接re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()),
]

修改:Django5Websocket/wsgi.py

import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
from chat.routing import websocket_urlpatternsos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Django5Websocket.settings')django_asgi_app = get_asgi_application()
application = ProtocolTypeRouter({"http": django_asgi_app,"websoket": AllowedHostsOriginValidator(AuthMiddlewareStack(URLRouter(websocket_urlpatterns)))
})

修改:chat/views.py

from django.shortcuts import renderdef index(request):"""首页路由"""return render(request, "chat/index.html")def room(request, room_name):"""房间路由"""return render(request, "chat/room.html", {"room_name": room_name})

新增:chat/templates/chat/room.html

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"/><title>Chat Room</title>
</head>
<body>
{#聊天日志#}
<textarea id="chat-log" cols="100" rows="20"></textarea><br>
{#消息输入框#}
<input id="chat-message-input" type="text" size="100"><br>
{#提交按钮#}
<input id="chat-message-submit" type="button" value="Send">
{#房间名称#}
{{ room_name|json_script:"room-name" }}
<script>// 提取房间名称const roomName = JSON.parse(document.getElementById('room-name').textContent);// 创建websocket连接const chatSocket = new WebSocket('ws://'+ window.location.host+ '/ws/chat/'+ roomName+ '/');// 接收消息chatSocket.onmessage = function (e) {// 解析接收到的消息const data = JSON.parse(e.data);// 输出到聊天日志记录document.querySelector('#chat-log').value += (data.message + '\n');};// 关闭websocketchatSocket.onclose = function (e) {console.error('聊天websocket连接已经被关闭');};// 消息输入框自动聚焦document.querySelector('#chat-message-input').focus();// 消息输入框的enter事件document.querySelector('#chat-message-input').onkeyup = function (e) {if (e.key === 'Enter') {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;// 发送消息chatSocket.send(JSON.stringify({'message': message}));// 清空输入框内容messageInputDom.value = '';};
</script>
</body>
</html>

迁移数据:

python manage.py migrate

Docker安装Redis

安装Redis:

docker run --restart=always -p 6379:6379 --name redis -d redis:7.0.12  --requirepass zhangdapeng520

安装依赖:

pip install channels_redis

配置信息:

ASGI_APPLICATION = 'Django5Websocket.asgi.application'
CHANNEL_LAYERS = {"default": {"BACKEND": "channels_redis.core.RedisChannelLayer","CONFIG": {"hosts": ["redis://:zhangdapeng520@127.0.0.1:6379/0"],},},
}

启动服务

启动服务,浏览器访问:http://localhost:8000/chat/test/

这篇关于在Django5中使用Websocket进行通信的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/552766

相关文章

Python在二进制文件中进行数据搜索的实战指南

《Python在二进制文件中进行数据搜索的实战指南》在二进制文件中搜索特定数据是编程中常见的任务,尤其在日志分析、程序调试和二进制数据处理中尤为重要,下面我们就来看看如何使用Python实现这一功能吧... 目录简介1. 二进制文件搜索概述2. python二进制模式文件读取(rb)2.1 二进制模式与文本

SQL Server 中的表进行行转列场景示例

《SQLServer中的表进行行转列场景示例》本文详细介绍了SQLServer行转列(Pivot)的三种常用写法,包括固定列名、条件聚合和动态列名,文章还提供了实际示例、动态列数处理、性能优化建议... 目录一、常见场景示例二、写法 1:PIVOT(固定列名)三、写法 2:条件聚合(CASE WHEN)四、

C#中checked关键字的使用小结

《C#中checked关键字的使用小结》本文主要介绍了C#中checked关键字的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录✅ 为什么需要checked? 问题:整数溢出是“静默China编程”的(默认)checked的三种用

C#中预处理器指令的使用小结

《C#中预处理器指令的使用小结》本文主要介绍了C#中预处理器指令的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录 第 1 名:#if/#else/#elif/#endif✅用途:条件编译(绝对最常用!) 典型场景: 示例

Mysql中RelayLog中继日志的使用

《Mysql中RelayLog中继日志的使用》MySQLRelayLog中继日志是主从复制架构中的核心组件,负责将从主库获取的Binlog事件暂存并应用到从库,本文就来详细的介绍一下RelayLog中... 目录一、什么是 Relay Log(中继日志)二、Relay Log 的工作流程三、Relay Lo

使用Redis实现会话管理的示例代码

《使用Redis实现会话管理的示例代码》文章介绍了如何使用Redis实现会话管理,包括会话的创建、读取、更新和删除操作,通过设置会话超时时间并重置,可以确保会话在用户持续活动期间不会过期,此外,展示了... 目录1. 会话管理的基本概念2. 使用Redis实现会话管理2.1 引入依赖2.2 会话管理基本操作

Springboot请求和响应相关注解及使用场景分析

《Springboot请求和响应相关注解及使用场景分析》本文介绍了SpringBoot中用于处理HTTP请求和构建HTTP响应的常用注解,包括@RequestMapping、@RequestParam... 目录1. 请求处理注解@RequestMapping@GetMapping, @PostMappin

springboot3.x使用@NacosValue无法获取配置信息的解决过程

《springboot3.x使用@NacosValue无法获取配置信息的解决过程》在SpringBoot3.x中升级Nacos依赖后,使用@NacosValue无法动态获取配置,通过引入SpringC... 目录一、python问题描述二、解决方案总结一、问题描述springboot从2android.x

SpringBoot整合AOP及使用案例实战

《SpringBoot整合AOP及使用案例实战》本文详细介绍了SpringAOP中的切入点表达式,重点讲解了execution表达式的语法和用法,通过案例实战,展示了AOP的基本使用、结合自定义注解以... 目录一、 引入依赖二、切入点表达式详解三、案例实战1. AOP基本使用2. AOP结合自定义注解3.

Python中Request的安装以及简单的使用方法图文教程

《Python中Request的安装以及简单的使用方法图文教程》python里的request库经常被用于进行网络爬虫,想要学习网络爬虫的同学必须得安装request这个第三方库,:本文主要介绍P... 目录1.Requests 安装cmd 窗口安装为pycharm安装在pycharm设置中为项目安装req