使用库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'),