python+django+dwebsocketは簡単なチャットルームを実現し、リアルタイムのオンラインを監視するユーザーとして機能します.

3908 ワード

ライブラリ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 :



    django-websocket
    
    
    $(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   ');
            }
        });

    });
    



Received Messages


urls.py :
url(r'^echo/(?P[0-9]+)$', views.echo, name='echo'),