码迷,mamicode.com
首页 > Web开发 > 详细

django使用websocket

时间:2019-12-30 11:22:10      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:div   djang   hat   Django项目   dem   一个   http和web   实现   self   

    WebSocket协议是基于TCP的一种新的协议。WebSocket最初在HTML5规范中被引用为TCP连接,作为基于TCP的套接字API的占位符。它实现了浏览器与服务器全双工(full-duplex)通信。其本质是保持TCP连接,在浏览器和服务端通过Socket进行通信

 

 

django 使用websocket需要安装channels

pip3 install channels==2.3 -i https://pypi.tuna.tsinghua.edu.cn/simple

 

创建django项目

  在settings.py里注册channels

INSTALLED_APPS = [
    django.contrib.admin,
    django.contrib.auth,
    django.contrib.contenttypes,
    django.contrib.sessions,
    django.contrib.messages,
    django.contrib.staticfiles,
    app01.apps.App01Config,
    # 项目中要使用channels做websocket了.
    "channels",
]

  本质: channels会把原来只支持http协议的wsgi,换成支持http和websocket协议的asgi

 

配置application

 

# settings.py 

INSTALLED_APPS = [
    django.contrib.admin,
    django.contrib.auth,
    django.contrib.contenttypes,
    django.contrib.sessions,
    django.contrib.messages,
    django.contrib.staticfiles,
    app01.apps.App01Config,
    # 项目中要使用channels做websocket了.
    "channels",
]

ASGI_APPLICATION = "channel_demo.routing.application"

 

# channel_demo/routing.py(新建routing.py文件)
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from app01 import consumers
application = ProtocolTypeRouter({
‘websocket‘: URLRouter([
url(r‘^chat/$‘, consumers.ChatConsumer),
])
})

app下建立consumers文件

 

和view文件功能一样,专门处理websocket请求
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

CONSUMER_OBJECT_LIST = []

class ChatConsumer(WebsocketConsumer):

    def websocket_connect(self, message):
        """
        客户端发来连接请求之后就会被触发
        :param message:
        :return:
        """
        # 服务端接收连接,向客户端浏览器发送一个加密字符串
        self.accept()
        # 连接成功
        CONSUMER_OBJECT_LIST.append(self)

    def websocket_receive(self, message):
        """
        客户端浏览器向服务端发送消息,此方法自动触发
        :param message:
        :return:
        """
        # 服务端给客户端回一条消息
        # self.send(text_data=message[‘text‘])
        for obj in CONSUMER_OBJECT_LIST:
            obj.send(text_data=message[text])
    def websocket_disconnect(self, message):
        """
        客户端主动断开连接
        :param message:
        :return:
        """
        # 服务端断开连接
        CONSUMER_OBJECT_LIST.remove(self)
        raise StopConsumer()

django使用websocket

标签:div   djang   hat   Django项目   dem   一个   http和web   实现   self   

原文地址:https://www.cnblogs.com/zhanghan5/p/12118359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!