当前位置: 首页 > 工具软件 > dwebsocket > 使用案例 >

dwebsocket 实现简易聊天室

苏波涛
2023-12-01

 view.py

from dwebsocket.decorators import accept_websocket,require_websocket
from collections import defaultdict
# 保存所有接入的用户地址
allconn = defaultdict(list)
@accept_websocket
def echo(request, userid):
    allresult = {}
    # 获取用户信息
    userinfo = User.objects.filter(id=userid).first()
    allresult['userinfo'] = userinfo
    # 声明全局变量
    global allconn
    if not request.is_websocket():#判断是不是websocket连接
        try:#如果是普通的http方法
            message = request.GET['message']
            from django.http import HttpResponse
            return HttpResponse(message)
        except:
            return render(request, '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)

url.py

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

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 + "/zhgd-system/user/echo/" + $('#userid').val());
            socket.onopen = function () {
                console.log('WebSocket open');//成功连接上Websocket
                window.s.send("用户"+ $('#username').val() + '加入 ' + getNowFormatDate() + ':<br>' + $('#message').val());//通过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.send("用户"+ $('#username').val() + '退出 ');
                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>聊天记录 </h1>
<div id="messagecontainer">

</div>
</body>
</html>

参考链接: https://www.cnblogs.com/huguodong/p/6611602.html

参考链接 : https://my.oschina.net/u/4255802/blog/3715270

Django WebSocket Redis 在线聊天室

 类似资料: