使用Django Channels构建WebSocket应用程序

2023-04-11 00:00:00 django 应用程序 构建

在使用Django Channels构建WebSocket应用程序之前,需要先安装Channels:

pip install channels

在settings.py中加入以下配置:

INSTALLED_APPS = [
    # ...
    'channels',
]
ASGI_APPLICATION = 'your_project_name.routing.application'

然后,在你的应用程序目录中创建一个名为routing.py的文件,内容如下:

from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from . import consumers

websocket_urlpatterns = [
    path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()),
]

application = ProtocolTypeRouter({
    'websocket': URLRouter(websocket_urlpatterns)
})

这里我们定义了一个名为“ChatConsumer”的消费者类,并让它处理所有的WebSocket请求。

下一步是实现上述ChatConsumer类。在你的应用程序目录中创建一个名为consumers.py的文件,内容如下:

from channels.generic.websocket import AsyncWebsocketConsumer

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def receive(self, text_data):
        # Receive message from WebSocket
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    async def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message
        }))

在我们的ChatConsumer中实现了三个方法:connect(),disconnect()和receive()。

接下来,在模板文件中,我们在JavaScript中创建一个WebSocket对象,连接到chat房间。

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Django Channels Chat Room</title>
    <script>
        var roomName = 'pidancode.com';
        var webSocketBridge = new channels.WebSocketBridge();
        webSocketBridge.connect('/ws/' + roomName);
        webSocketBridge.listen(function (data) {
            console.log("Received: " + data.message);
        });

        function sendMessage(message) {
            webSocketBridge.send({
                "message": message
            });
        }
    </script>
</head>
<body>
    <h1>Django Channels Chat Room</h1>
    <div id="chat">
        <input type="text" id="message">
        <button onclick="sendMessage(document.getElementById('message').value)">Send</button>
    </div>
</body>
</html>

这里我们创建了一个名为“webSocketBridge”的连接,将其连接到chat房间。sendMessage()函数用于发送消息。

这就是用Django Channels构建WebSocket应用程序的基本示例。

相关文章