引入

先安装三个模块

pip install channels

pip install channels_redis

pip install pywin32

创建一个Django项目和一个app

项目名随意,app名随意。这里项目名为django_websocket_demo,app名chat

把app文件夹下除了views.py__init__.py的文件都删了,最终项目目录结构如下:

django_websocket_demo/
manage.py
django_websocket_demo/
__init__.py
settings.py
urls.py
wsgi.py
chat/
__init__.py
views.py

在app下新建一个templates文件夹用来存放HTML页面:

chat/
__init__.py
templates/
chat/
index.html
views.py

index.html内容如下:

<!-- chat/templates/chat/index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Rooms</title>
</head>
<body>
What chat room would you like to enter?<br/>
<input id="room-name-input" type="text" size="100"/><br/>
<input id="room-name-submit" type="button" value="Enter"/> <script>
document.querySelector('#room-name-input').focus();
document.querySelector('#room-name-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#room-name-submit').click();
}
}; document.querySelector('#room-name-submit').onclick = function(e) {
var roomName = document.querySelector('#room-name-input').value;
window.location.pathname = '/chat/' + roomName + '/';
};
</script>
</body>
</html>

chat/views.py中添加视图函数:

from django.shortcuts import render

def index(request):
return render(request, 'chat/index.html', {})

添加 chat/urls.py文件并设置路由信息:

from django.urls import re_path

from . import views

urlpatterns = [
re_path(r'^$', views.index, name='index'),
]

在项目路由django_websocket_demo/urls.py中配置路由信息:

from django.conf.urls import include, url
from django.contrib import admin urlpatterns = [
url(r'^chat/', include('chat.urls')),
url(r'^admin/', admin.site.urls),
]

settings.py文件同级目录下新建routing.py文件,内容如下:

from channels.routing import ProtocolTypeRouter

application = ProtocolTypeRouter({
# (http->django views is added by default)
})

channels注册在settings.py里:

INSTALLED_APPS = [
'channels',
'chat',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

 settings.py文件中,添加如下配置项:

# django_websocket_demo/settings.py
# Channels
# Channels
ASGI_APPLICATION = 'django_websocket_demo.routing.application'

创建聊天页面

创建一个chat/templates/chat/room.html文件,添加如下内容:

<!-- 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"/>
</body>
<script>
var roomName = {{ room_name_json }}; var chatSocket = new WebSocket(
'ws://' + window.location.host +
'/ws/chat/' + roomName + '/'); chatSocket.onmessage = function(e) {
var data = JSON.parse(e.data);
var message = data['message'];
document.querySelector('#chat-log').value += (message + '\n');
}; chatSocket.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) {
var messageInputDom = document.querySelector('#chat-message-input');
var message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
})); messageInputDom.value = '';
};
</script>
</html>

chat/views.py中添加一个处理 room的视图函数:

from django.shortcuts import render
from django.utils.safestring import mark_safe
import json def index(request):
return render(request, 'chat/index.html', {}) def room(request, room_name):
return render(request, 'chat/room.html', {
'room_name_json': mark_safe(json.dumps(room_name))
})

chat/urls.py中注册路由

from django.urls import re_path

from . import views

urlpatterns = [
re_path(r'^$', views.index, name='index'),
re_path(r'^(?P<room_name>[^/]+)/$', views.room, name='room'),
]

新建chat/consumers.py文件,添加如下内容:

from channels.generic.websocket import AsyncWebsocketConsumer
import json class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name # Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
) await self.accept() async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
) # Receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message'] # Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
) # Receive message from room group
async def chat_message(self, event):
message = event['message'] # Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))

新建一个chat/routing.py文件,添加以下内容:

from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
re_path(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),
]

django_websocket_demo/routing.py文件中修改为以下内容:

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})

配置redis

在本地6379端口启动redis :redis-server

settings.py中添加如下配置:

CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}

最后启动Django项目

使用多个浏览器打开http://127.0.0.1:8000/chat/lobby/,开始实时聊天吧。

Django-channels 实现WebSocket实例的更多相关文章

  1. Django使用channels实现Websocket连接

    简述: 需求:消息实时推送消息以及通知功能,采用django-channels来实现websocket进行实时通讯.并使用docker.daphne启动通道,保持websocket后台运行 介绍Dja ...

  2. 实时 Django 终于来了 —— Django Channels 入门指南

    Reference: http://www.oschina.net/translate/in_deep_with_django_channels_the_future_of_real_time_app ...

  3. Django Channels 入门指南

    http://www.oschina.NET/translate/in_deep_with_django_channels_the_future_of_real_time_apps_in_django ...

  4. 【翻译】Django Channels 官方文档 -- Tutorial

    Django Channels 官方文档 https://channels.readthedocs.io/en/latest/index.html 前言: 最近课程设计需要用到 WebSocket,而 ...

  5. Django Channels 学习笔记

    一.为什么要使用Channels 在Django中,默认使用的是HTTP通信,不过这种通信方式有个很大的缺陷,就是不能很好的支持实时通信.如果硬是要使用HTTP做实时通信的话只能在客户端进行轮询了,不 ...

  6. django + nginx + uwsgi + websocket

    最近使用django框架做了一个简单的聊天机器人demo, 开发的过程中使用了django自带的websocket模块,当使用django框架自带的wsgi服务去启动的话,没有什么问题.如果要使用uw ...

  7. 通过Django Channels设计聊天机器人WEB框架

    这两个月都在忙着设计针对银联客服业务的智能聊天机器人,上一周已经交完设计报告,这一周还和部门同事一起分享了系统设计及运行效果.因为时间的关系,系统原型我使用了Flask+jQuery的组合,感觉用以原 ...

  8. django channels

    django channels django channels 是django支持websocket的一个模块. 1. 安装 `pip3 install channels` 2. 快速上手 2.1 在 ...

  9. Django中使用websocket并实现简易聊天室

    django使用websocket并实现简易聊天室 django默认只支持http协议 如果你想让django即支持http协议又支持websocket协议,则需要做以下配置 前期配置 前提需要安装c ...

随机推荐

  1. 【模拟】(正解树状数组)-校长的问题-C++-计蒜客

    描述 学校中有 n 名学生,学号分别为 1 - n.再一次考试过后,学校按照学生的分数排了一个名次(分数一样,按照名字的字典序排序).你是一名老师,你明天要和校长汇报这次考试的考试情况,校长询问的方式 ...

  2. 个人永久性免费-Excel催化剂功能第88波-批量提取pdf文件信息(图片、表格、文本等)

    日常办公场合中,除了常规的Excel.Word.PPT等文档外,还有一个不可忽略的文件格式是pdf格式,而对于想从pdf文件中获取信息时,常规方法将变得非常痛苦和麻烦.此篇给大家送一pdf文件提取信息 ...

  3. 个人永久性免费-Excel催化剂功能第66波-数据快速录入,预定义引用数据逐字提示

    在前面好几波的功能中,为数据录入的规范性做了很大的改进,数据录入乃是数据应用之根,没有完整.干净的数据源,再往下游的所有数据应用场景都是空话.在目前IT化进程推进了20多年的现状,是否还仍有必要在Ex ...

  4. [HDOJ] 1172.猜数字

    Problem Description 猜数字游戏是gameboy最喜欢的游戏之一.游戏的规则是这样的:计算机随机产生一个四位数,然后玩家猜这个四位数是什么.每 猜一个数,计算机都会告诉玩家猜对几个数 ...

  5. WPF依赖属性的正确学习方法

    前言 我在学习WPF的早期,对依赖属性理解一直都非常的不到位,其恶果就是,我每次在写依赖属性的时候,需要翻过去的代码来复制黏贴. 相信很多朋友有着和我相同的经历,所以这篇文章希望能帮助到那些刚刚开始学 ...

  6. kubernetes的volume的权限设置(属主和属组)

    apiVersion: v1kind: Podmetadata: name: hello-worldspec:  containers:  # specification of the pod's c ...

  7. 《VR入门系列教程》之17---发布第一个应用

    发布运行     Unity可以支持多种目标平台的发布,包括:桌面端.Web端.移动端.游戏主机端.     发布运行之前的Cubes场景至桌面端,我们先选择File->Build Settin ...

  8. configASSERT( uxCriticalNesting == ~0UL );问题

    今天在单步调试FreeRTOS时,一直进入port.c 中的configASSERT( uxCriticalNesting == ~0UL ):函数.照片如下 上网一查,并且结合这个英文注释,才发现, ...

  9. get解决乱码的方式

    //自定义的解决乱码方式

  10. ES 23 - 检索和过滤的区别 (query vs. filter)

    目录 1 filter与query示例 1.1 准备测试数据 1.2 搜索测试 2 filter与query的区别 2.1 相关度处理上的不同 2.2 性能上的对比 2.3 对比结论 本文以 ES 6 ...