python + django + dwebsocket 實現簡單的聊天室


使用庫dwebsocket,具體參考此處

views.py:

from dwebsocket.decorators import accept_websocket,require_websocket
from collections import defaultdict
# 保存所有接入的用戶地址
allconn = defaultdict(list)
@accept_websocket
def echo(request, userid):
    allresult = {}
    # 獲取用戶信息
    userinfo = request.user
    allresult['userinfo'] = userinfo
    # 聲明全局變量
    global allconn
    if not request.is_websocket():#判斷是不是websocket連接
        try:#如果是普通的http方法
            message = request.GET['message']
            return HttpResponse(message)
        except:
            return render(request, 'myproject/chat.html', allresult)
    else:
        # 將鏈接(請求?)存入全局字典中
        allconn[str(userid)] = request.websocket
        # 遍歷請求地址中的消息
        for message in request.websocket:
            # 將信息發至自己的聊天框
            request.websocket.send(message)
            # 將信息發至其他所有用戶的聊天框
            for i in allconn:
                if i != str(userid):
                    allconn[i].send(message)

chat.html :

<!DOCTYPE html>
<html>
<head>
    <title>django-websocket</title>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {
        // 獲取當前時間的函數
        function getNowFormatDate() {
            var date = new Date();
            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                    + " " + date.getHours() + seperator2 + date.getMinutes()
                    + seperator2 + date.getSeconds();
            return currentdate;
        }
 
        $('#connect_websocket').click(function () {
            if (window.s) {
                window.s.close()
            };
            /*創建socket連接*/
            var socket = new WebSocket("ws://" + window.location.host + "/myproject/echo/" + $('#userid').val());
            socket.onopen = function () {
                console.log('WebSocket open');//成功連接上Websocket
            };
            socket.onmessage = function (e) {
                console.log('message: ' + e.data);//打印出服務端返回過來的數據
                $('#messagecontainer').prepend('<p>' + e.data + '</p>');
            };
            // Call onopen directly if socket is already open
            if (socket.readyState === WebSocket.OPEN) socket.onopen();
            window.s = socket;
        });
        $('#send_message').click(function () {
            //如果未連接到websocket
            if (!window.s) {
                alert("websocket未連接.");
            } else {
                window.s.send($('#username').val() + ' ' + getNowFormatDate() + ':<br>' + $('#message').val());//通過websocket發送數據
            }
        });
        $('#close_websocket').click(function () {
            if (window.s) {
                window.s.close();//關閉websocket
                console.log('websocket已關閉');
            }
        });
 
    });
    </script>
</head>
<body>
<br>
<input type="hidden" id="userid" value="{{ userinfo.id }}"/>
<input type="hidden" id="username" value="{{ userinfo.username }}"/>
<input type="text" id="message" value="Hello, World!"/>
<button type="button" id="connect_websocket">連接 websocket</button>
<button type="button" id="send_message">發送 message</button>
<button type="button" id="close_websocket">關閉 websocket</button>
<h1>Received Messages</h1>
<div id="messagecontainer">
 
</div>
</body>
</html>

urls.py :

url(r'^echo/(?P<userid>[0-9]+)$', views.echo, name='echo'),

 

閱讀原文

Django WebSocket Redis 在線聊天室

https://github.com/huguodong/dj_dwebsocket(demo代碼)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM