跳转至

Django-websocket

使用方法有很多,下面就就自己喜欢的工具 uvicorn 的使用方法进行介绍。

环境安装

依赖

pip install 'uvicorn[standard]' channels channels_redis

配置

asgi.py
import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from django.urls import  re_path

from app import consumers

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Assetinventory.settings')
application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
        URLRouter([
            re_path("msg/chat/", consumers.MyConsumer.as_asgi()),
        ])
    ),
})
consumers.py
class MyConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_group_name = "meet"

        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        await self.accept()
        await send_message_to_group("meet","Hello, group members!")  # 向组发送消息

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def message(self, event):
        message = event['text']
        await self.send(text_data=message)

    async def chat_message(self, event):
        message = event['message']

        # 发送消息到 WebSocket
        await self.send(text_data=json.dumps({
            'message': message
        }))
前端模板index.html
<input id="messageInput" type="text">
<button id="sendButton">Send</button>
<ul id="chatLog"></ul>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    var chatSocket = new WebSocket(
        'ws://' + window.location.host + '/msg/chat/'
    );
    chatSocket.onmessage = function (e) {
        $('#chatLog').append('<li>' + e.data + '</li>');
    };
    $('#sendButton').click(function () {
        var messageInputDom = $('#messageInput');
        var message = messageInputDom.val();
        chatSocket.send(JSON.stringify({
            'message': message
        }));
        messageInputDom.val('');
    });
</script>

使用

访问F12 可以看到ws连接成功

输入消息后点击发送按钮,可以查看到消息发送成功,且返回

输出一秒返回一个
{"message":"666"}
Hello, world! - 0
Hello, world! - 1
Hello, world! - 2
Hello, world! - 3
Hello, world! - 4
Hello, world! - 5
Hello, world! - 6
Hello, world! - 7
Hello, world! - 8
Hello, world! - 9

其他方法发送消息

使用redis 作为 消息队列

settings.py
1
2
3
4
5
6
7
8
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

外部方法 向websocket发送消息

核心就是在方法中 加入组
1
2
3
4
5
6
7
async def connect(self):
    self.room_group_name = "meet"
    #-------------------------------- 核心
    await self.channel_layer.group_add(
        self.room_group_name,
        self.channel_name
    )
调用下面的方法即可独立发送消息
async def send_message_to_group(room_group_name,message):
    channel_layer = get_channel_layer()

    await channel_layer.group_send(
        room_group_name,
        {
            'type': 'chat_message',
            'message': message
        }
    )