代码发布2
django基于channels实现群聊功能
其实除了可以在全局创建模版文件夹之外,还可以做到更加的细化 就是在每一个应用下创templates模版文件夹
如果出现多个应用和全局都有模版文件夹的情况,那么会优先查找全局 如果全局没有,则按照配置文件中注册app的顺序的从上往下一次查找每一个应用下templates
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',
]
每一个应用都可以有自己的urls.py(路由分发),views.py,templates,static
-
首先先配置好让django支持websocket和http
#配置完成后同时支持http和websocket的原因(源码)
class ProtocolTypeRouter:
"""
Takes a mapping of protocol type names to other Application instances,
and dispatches to the right one based on protocol name (or raises an error)
"""
def __init__(self, application_mapping):
self.application_mapping = application_mapping
if "http" not in self.application_mapping:
self.application_mapping["http"] = AsgiHandler
-
配置routing 的路由分发,新建一个类似于views的视图文件consumers.py
# routing.py
from channels.routing import ProtocolTypeRouter,URLRouter
from django.conf.urls import url
from app01 import consumers
application = ProtocolTypeRouter({
'websocket':URLRouter([
# websocket相关路由
url(r'^chat', consumers.ChatConsumer)
])
})
-
在 consumers.py中写视图类ChatConsumer
from channels.generic.websocket import WebsocketConsumer
class ChatConsumer(WebsocketConsumer):
# 三个内置方法
def websocket_connect(self, message):
"""客户端请求建立链接时 自动触发"""
pass
def websocket_receive(self, message):
"""客户端发送数据过来 自动触发"""
pass
def websocket_disconnect(self, message):
"""客户端断开链接之后 自动触发"""
pass
完整的群聊代码
#urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
]
# views.py
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
# app01.templates.index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h1>聊天室</h1>
<input type="text" id="text">
<button onclick="sendMsg()">发送</button>
<h1>聊天记录</h1>
<div class="recode"></div>
{#这句代码很重要,可以让urls.py文件的index路由访问这个地址,实现websocket协议#}
<script>
var ws = new WebSocket('ws://127.0.0.1:8000/chat/');
// 1 握手环节验证成功之后 自动触发 onopen
ws.onopen = function () {
console.log('握手成功')
}
// 2 给服务端发送消息 send
function sendMsg() {
ws.send($('#txt').val())
}
// 3 一旦服务端有消息 自动触发 onmessage
ws.onmessage = function (args) {
// console.log(args) // args是一个对象
// 获取发送的数据
{#console.log(args.data)#}
{#alert(args.data)#}
// 1 创建p标签
var pEle = $('<p>');
pEle.text(args.data);
$('.record').append(pEle)