django-channels小结

来源:互联网 发布:js 仿京东楼层特效 编辑:程序博客网 时间:2024/06/05 11:38

为什么使用django-channels: 在项目实际开发过程中需要实现客户端(浏览器)与服务器之间的实时通信。

websockets: websockets是一种新的全双工通信协议,一个持久的,可以在任何时间发送数据的客户端与服务器之间的链接。

项目中的几个重要配置:

一、服务器端

1.使用asgi替代wsgi:

asgi.py

# coding: utf-8'''Created on 2017年3月2日@author: win7'''import osfrom channels.asgi import get_channel_layeros.environ.setdefault("DJANGO_SETTINGS_MODULE", "ChannelsDemo.settings")channel_layer = get_channel_layer()

2.settings配置:

注册应用:


使用redis作为消息传输通道层:


3.channels路由层配置:

#coding: utf-8'''Created on 2017年5月17日@author: win7''''''路由层,可以理解为django中的urls.py'''from channels.routing import route, includefrom channels.staticfiles import StaticFilesConsumerimport consumerschannel_routing = [    route('http.request', StaticFilesConsumer),    route('websocket.connect', consumers.ws_connect),    route('websocket.receive', consumers.ws_receive),    route('websocket.disconnect', consumers.ws_disconnect),]routing = [    include(channel_routing, path=r"^/test"),]
4.channels消费者层:

# coding: utf-8'''Created on 2017年5月17日@author: win7'''from channels.sessions import channel_sessionfrom channels import Group@channel_sessiondef ws_connect(message):    Group('chat-'+'test', channel_layer=message.channel_layer).add(message.reply_channel)    message.channel_session['room'] = 'test'    @channel_sessiondef ws_receive(message):    label = message.channel_session['room']    Group('chat-'+label, channel_layer=message.channel_layer).send({'text': 'hello world!'})    @channel_sessiondef ws_disconnect(message):    label = message.channel_session['room']    Group('chat-'+label, channel_layer=message.channel_layer).discard(message.reply_channel)

二、客户端(页面html)

如何通过javascript定义一个websocket并进行消息的发送及响应:

{% load static %}<script type="text/javascript" src="{% static "jquery-1.7.2.min.js"  %}"></script><!-- 该js的作用是在websocket连接失败/断开时自动请求重新连接 --><script type="text/javascript" src="{% static "reconnecting-websocket.min.js"  %}"></script><!-- js发送websocket请求 --><script>var chatsock;$(function(){// 在使用https协议时使用wssvar ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";// 定义一个websocket对象 ps: ReconnectingWebSocket类参数为websocket请求的urlchatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/test");// 收到来自服务器的websocket响应时触发的回调函数 ps: 相当于Ajax请求success回调函数chatsock.onmessage = function(message) {console.log("服务器说:", message.data);document.write("服务器说:"+message.data);}});function sendWebSocket(){// 向服务器发送一个websocket请求chatsock.send("hello server!");}</script><button onclick="sendWebSocket()">发送websocket</button>
三、效果展示




原创粉丝点击