SoFunction
Updated on 2024-11-15

Django WebSocket online chat room functionality (channels library)

Implementing WebSocket Online Chat Rooms

1.1 Installation

pip install channels==2.3

(saas) F:\Desktop\Python_Study\CHS-Tracer\saas>pip install channels==2.3
Looking in indexes: /pypi/simple/
Collecting channels==2.3
  Downloading
  ...
Successfully installed Automat-20.2.0 attrs-20.3.0 autobahn-21.3.1 channels-2.3.0

1.2 Creating a Django Project

1.3 http routing

url(r"^chat/$", chat_view.chat, name="chat"), # chat room

1.4 http view functions

def chat(request):
    return render(request, "")

1.5 settings add channels related configuration

INSTALLED_APPS = [
    'channels',  # It's time to use channels for WebSocket in the project.
]

ASGI_APPLICATION = "" # Project Name.

1.6 Creating (routes for websockets) and (view functions for websockets)

1.7 websocket routing

# -*- coding:utf-8 -*-
# By Cai Tuotuo, an IT student #
# Time: 2021/4/23 18:21
# Function: channels related routing

from  import ProtocolTypeRouter, URLRouter
from  import url

from web import consumers

application = ProtocolTypeRouter({
    "websocket": URLRouter([
        url(r'^chat/$', ),
    ])
})

1.8 websocket view functions

# -*- coding:utf-8 -*-
# By Cai Tuotuo, an IT student #
# Time: 2021/4/23 18:25
# Function: Channels related view

from  import StopConsumer
from  import WebsocketConsumer

# Define a list of users who are currently online
CONSUMER_OBJECT_LIST = []


class ChatConsumer(WebsocketConsumer):

    def websocket_connect(self, message):
        """
        Triggered after a connection request from the client browser
        :param message.
        :return.
        """

        # The server receives the connection and sends an encrypted string to the client browser
        ()
        # Connection successful
        CONSUMER_OBJECT_LIST.append(self)

    def websocket_receive(self, message):
        """
        The client browser sends a message to the server, this method is triggered automatically
        :param message.
        :return.
        """

        print("Message accepted.", message)

        # The server sends a message back to the client
        # (text_data=message["text"])
        for obj in CONSUMER_OBJECT_LIST:
            (text_data=message["text"])

    def websocket_disconnect(self, message):
        """
        Client browser active disconnect
        :param message.
        :return.
        """

        # The server disconnects
        CONSUMER_OBJECT_LIST.remove(self)
        raise StopConsumer()

1.9 Front-end code

<!-- csstype -->
<style>
    pre {
        display: block;
        padding: 9.5px;
        margin: 0 0 10px;
        font-size: 18px;
        line-height: 1.42857143;
        color: #333;
        word-break: break-all;
        word-wrap: break-word;
        background-color: #00aaaa;
        border-radius: 12px;
    }
</style>

<!-- bodyelement -->
<div style="width: 600px;height: 574px;margin: auto;margin-top: 20px;">
    <div class="panel panel-success">
        <div class="panel-heading">Online Live Chat Room</div>
        <div class="panel-body">
            <div style="border: #f5f5f5 2px solid;width: 570px;height: 400px;overflow:scroll">
                <div >
                    <!-- chat log -->
                </div>
            </div>
            <div style="border-color: white;margin-top: 10px">
                <textarea type="text"  placeholder="Please enter message content ......" class="form-control"></textarea>
            </div>
        </div>

        <div class="table">
            <div>
                <button class="btn btn-danger" onclick="closeLink();" style="margin-left: 74%">Disconnect</button>
                <button class="btn btn-success" onclick="sendMsg();">dispatch</button>
            </div>
        </div>
    </div>
</div>

<!-- Message templates -->
<div  class="hide">
    <div class="right-info">
        <!-- subscribers -->
        <p>匿名subscribers:</p>

        <!-- 消息element -->
        <pre>

            </pre>
    </div>
</div>


<!-- jscoding -->
<script>
    var STATUS; // Flag for whether to connect
    var ws = new WebSocket("ws://127.0.0.1:8000/chat/");

     = function () {
        // The client automatically executes this method after the handshake session has been successfully verified
        ("Connection successful.")
    };

     = function msg(event) {
        var $item = $("#recordTemplate").find('.right-info').clone();
        $('pre').html();
        $("#content").append($item);
    };

    function sendMsg() {
        if (STATUS == false) {
            swal({
                title: "Disconnected.",
                text: "Currently disconnected, refresh page to reconnect."
            });
        } else {
            ($("#txt").val());
            $("#txt").val("");
        }
    }

    function closeLink() {
        ();
        STATUS = false;
        ("Disconnect.");
        swal({
            text: "Successfully disconnected, refresh page to reconnect."
        });
    }
</script>

2.Effect display

3. Summary

http protocol
chat routing --> chat view function
Access: just send a request from your browser
websocket protocol
chat routing --> ChatConsumer (3 methods)
Access: new WebSocket object

This article on the Django WebSocket online chat room (channels library) is introduced to this article , more related Django WebSocket online chat room content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future !