【webSokect】基于django Channels的简单实现

# settings.py:

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

ASGI_APPLICATION = "webSokect.routing.application"
# routing.py


#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from api import consumers


application = ProtocolTypeRouter({
    'websocket': URLRouter([
        url(r'^chat/$', consumers.ChatConsumer),
    ])
})
# consumers.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

CLIENTS = []


class ChatConsumer(WebsocketConsumer):

    def websocket_connect(self, message):
        self.accept()
        CLIENTS.append(self)

    def websocket_receive(self, text_data=None, bytes_data=None):
        # print("message",text_data)
        for item in CLIENTS:
            item.send(text_data['text'])

        # self.send(text_data['text'])

    def websocket_disconnect(self, message):
        print('客户端断开连接了')
        CLIENTS.remove(self)
        raise StopConsumer()
# chat.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Talking</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <style>
        #taking {
            width: 100%;
            height: 700px;
            background: #42fbff;
        }
    </style>
</head>
<body>
<div id="app" class="container">
    <div class="card-header">在线聊天室</div>
    <div id="taking">
        <ul id="uls">

        </ul>
    </div>
    <div style=" 100%;height: 80px">
        <textarea type="text" id="txt" placeholder="请输入内容" style=" 100%;height: 100%"></textarea>
    </div>
    <button class="btn btn-primary" style=" 100px" id="sendMsg">发送</button>
    <button class="btn btn-danger" style=" 100px" id="close">断开连接</button>
</div>
</body>
</html>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
    var ws = new WebSocket("ws://127.0.0.1:8001/chat/")

    // 检测是否连接成功
    ws.onopden = function(event){
        console.log("成功连接");
    };

    // 接受消息
    ws.onmessage = function(event){
        {#console.log("消息",event.data);#}
        var tag = $("<li>" + event.data + "</li>")
        {#console.log(tag)#}
        {#tag.text(event.data)#}
        $("#uls").append(tag)
    }

    // 发送
    $("#sendMsg").click(function () {
        ws.send($("#txt").val())
    })

    // 关闭
    $("#close").click(function () {
        ws.close()
        console.log("断开成功");
    })

    
</script>

原文地址:https://www.cnblogs.com/wanghong1994/p/13997937.html