Django实现websocket

 

django实现websocket大致上有两种方式,一种channels,一种是dwebsocket。channels依赖于redis,twisted等

一 dwebsocket

1 Django实现Websocket

django实现websocket大致上有两种方式,一种channels,一种是dwebsocket。channels依赖于redis,twisted等,相比之下使用dwebsocket要更为方便一些

2 dwebsocket安装

pip3 install dwebsocket

3 dwebsocket配置

setting 设置

INSTALLED_APPS = [
    ...
    ...   
    'dwebsocket'
]
import dwebsocket
MIDDLEWARE_CLASSES = [
    'dwebsocket.middleware.WebSocketMiddleware'  # 为所有的URL提供websocket,如果只是单独的视图需要可以不选
]
WEBSOCKET_ACCEPT_ALL=True                # 可以允许每一个单独的视图实用websockets

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'^login/', views.login),
    url(r'^path/', views.path),
]

views.py

from django.shortcuts import render


def login(request):
    return render(request, 'index.html')


from dwebsocket.decorators import accept_websocket


@accept_websocket
def path(request):
    if request.is_websocket():
        print(1)
        request.websocket.send('下载完成'.encode('utf-8'))

html

<body>
  <button onclick="WebSocketTest()">test</button>
</body>


<script>
    function WebSocketTest() {
        if ("WebSocket" in window) {
            alert("您的浏览器支持 WebSocket!");

            // 打开一个 web socket
            var ws = new WebSocket("ws://127.0.0.1:8000/path/");
            console.log('ws',ws)

            ws.onopen = function () {
                // Web Socket 已连接上,使用 send() 方法发送数据
                ws.send("发送数据");
                alert("数据发送中...");
            };

            ws.onmessage = function (evt) {
                var received_msg = evt.data;
                alert("数据已接收...");
                alert("数据:" + received_msg)
            };

            ws.onclose = function () {
                // 关闭 websocket
                alert("连接已关闭...");
            };
        }

        else {
            // 浏览器不支持 WebSocket
            alert("您的浏览器不支持 WebSocket!");
        }
    }
</script>

4 dwesocket的参数

dwebsocket有两种装饰器:require_websocket和accept_websocekt,使用require_websocket装饰器会导致视图函数无法接收导致正常的http请求,一般情况使用accept_websocket方式就可以了,

 

dwebsocket的一些内置方法:

 

 

request.is_websocket():判断请求是否是websocket方式,是返回true,否则返回false

request.websocket():当请求为websocket的时候,会在request中增加一个websocket属性,

WebSocket.wait():返回客户端发送的一条消息,没有收到消息则会导致阻塞

WebSocket.read() 和wait一样可以接受返回的消息,只是这种是非阻塞的,没有消息返回None

WebSocket.count_messages():返回消息的数量

WebSocket.has_messages():返回是否有新的消息过来

WebSocket.send(msg):像客户端发送消息,message为byte类型

 

二 channels

1 channels在pypi上可以用以下代码安装

pip3 install -U channels

2.settings配置

一旦你安装了,你应该添加 channels 到您的  INSTALLED_APPS 

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
   ...
   ...

    'channels',
]

还有要添加

ASGI_APPLICATION = "django_channels_demo.routing.application"

3. 创建websocket应用和路由

我们将从一个空的路由配置开始。创建一个文件,项目名/routing.py并包含以下代码:

# 项目名/routing.py
from channels.routing import ProtocolTypeRouter

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

 

后面就可以啦启动了

详见官网

 

 

posted @ 2019-12-08 15:33  流年中渲染了微笑  阅读(1001)  评论(0编辑  收藏  举报