最近看到好多設(shè)計(jì)類(lèi)網(wǎng)站,都提供了多人在線匿名聊天的小功能,感覺(jué)很有意思,于是基于python/280944.html">python的django框架自己寫(xiě)了一個(gè),支持手動(dòng)實(shí)時(shí)更名,最下方提供了完整的源碼.
在線聊天地址(無(wú)需登錄,開(kāi)一個(gè)窗口,代表一個(gè)用戶(hù)):
http://zhaozhaoli.vicp.io/chatroom/happy/
移動(dòng)端聊天效果圖:

網(wǎng)頁(yè)版聊天效果圖:

實(shí)現(xiàn)思路:
發(fā)送的消息通過(guò)ajax先寫(xiě)入數(shù)據(jù)庫(kù),通過(guò)ajax的循環(huán)請(qǐng)求,將寫(xiě)入數(shù)據(jù)庫(kù)的消息顯示到前端界面.
前端核心代碼:
<script> $(function () { $("#send").click(function () { var input_info = $("#input_info").val(); if (input_info.length < 1) { alert("請(qǐng)輸入字符后發(fā)送"); return; } else if (input_info.length > 200) { alert("每次發(fā)送不可以超出200個(gè)字符哈~"); return; } else { // 獲取csrftoken的值 var csrf_value = $('#csrfmiddlewaretoken').text(); var user_id = $("#user_id").text(); var user_name = $("#user_name").text(); $.ajax({ 'url': '/chatroom/save_chat_log/', 'data': { 'chat_content': input_info, 'user_id': user_id, 'user_name': user_name, 'user_ip': '127.127.127.127', 'csrfmiddlewaretoken': csrf_value }, 'type': 'post', 'async': false, 'success': function (data) { } }); $("#input_info").val(""); console.log($("#show_info").scrollTop()); } }) })</script><script> var user_id = $("#user_id").text(); var user_name = $("#user_name").text(); $(function () { var last_id = 0; var csrf_value2 = $('#csrfmiddlewaretoken').text(); function update_info() { // ajax 獲取最新數(shù)據(jù) $.ajax({ 'url': '/chatroom/get_near_log/', 'data':{"last_id":last_id,'csrfmiddlewaretoken': csrf_value2}, 'type':'post', 'async': false, 'success':function (data) { if (parseInt(last_id) == parseInt(JSON.parse(data.data).last_id)){ return; } //獲取后臺(tái)傳過(guò)來(lái)的id值,并將值存儲(chǔ)到全局變量中 last_id = JSON.parse(data.data).last_id; // 將內(nèi)容讀取,并打印 content = JSON.parse(data.data).info; for (var i=0; i< content.length; i++){ if (parseInt(content[i].user_id) == parseInt($("#user_id").text())){ var html = "<div class='my_info'><span>"+content[i].user_name+"</span></div>"; html = html + "<div class='my_one_info'>"+content[i].mess+"</div>"; $("#content").append(html); }else{ var html = "<div class='other_info'><span>"+content[i].user_name+"</span></div>"; html = html + "<div class='other_one_info'>"+content[i].mess+"</div>"; $("#content").append(html); } $("#show_info").scrollTop($("#content").height()) } } }) } update_info(); setInterval(update_info, 1000); })</script><script> $(function () { //監(jiān)聽(tīng)鍵盤(pán)點(diǎn)擊 $(document).keyup(function (event) { if (event.keyCode == 13){ $("#send").click(); } }) })</script><script> $(function () { $("#change_name").click(function () { // 獲取新名稱(chēng) var new_name = String($("#new_name").val()); // 檢查新名稱(chēng)是否合法 // 如果合法 if (new_name.length<11 && new_name.length>0){ console.log(new_name); $("#user_name").text(new_name); $("#new_name").val("") }else{ alert("昵稱(chēng)長(zhǎng)度應(yīng)為1-10,請(qǐng)重新輸入"); $("#new_name").val("") } }) })</script><div id="main_form"> <div class="my_nike_name">我的昵稱(chēng):<span id="user_name">{{user_name}}</span><span><button id="change_name">更名</button><input type="text" id="new_name"></span></div> <div id="show_info"> <div id="content"> </div> </div> <br> <div class="my_nike_name">消息</div> <input type="text" id="input_info"> <button id="send">發(fā)送消息</button> <div id="user_id" style="display: none">{{user_id}}</div> <div id="user_ip" style="display: none">{{user_ip}}</div> <span id ="csrfmiddlewaretoken" style="display: none">{{csrf_token}}</span></div>后端核心代碼:
# 返回基礎(chǔ)頁(yè)面def happy(request): user_info = UserInfo() # 初始用戶(hù)名為匿名用戶(hù) user_name = "匿名用戶(hù)" user_info.user_name = user_name # 利用時(shí)間產(chǎn)生臨時(shí)ID user_id = int(time.time()) user_info.user_id = user_id # 獲取用戶(hù)ip user_ip = wrappers.get_client_ip(request) user_info.user_ip = user_ip user_info.save() return render(request, 'chatroom/happy.html', locals())# 保存聊天內(nèi)容def save_chat_log(request): try: print("后端收到了ajax消息") chatinfo = ChatInfo() # 獲取前端傳過(guò)來(lái)的數(shù)據(jù) chat_content = wrappers.post(request, "chat_content") user_ip = wrappers.get_client_ip(request) user_name = wrappers.post(request, "user_name") user_id = wrappers.post(request, "user_id") # 將數(shù)據(jù)存入數(shù)據(jù)庫(kù) chatinfo.chat_content = chat_content chatinfo.user_ip = user_ip chatinfo.user_name = user_name chatinfo.user_id = user_id chatinfo.save() return JsonResponse({"ret":0}) except: return JsonResponse({"ret":"保存出現(xiàn)問(wèn)題"}) pass# 獲取最近的聊天信息def get_near_log(request): try: # 獲取數(shù)據(jù)庫(kù)內(nèi)所有的信息 all_info = ChatInfo.objects.all() # 獲取數(shù)據(jù)庫(kù)內(nèi)最后一條消息的id id_max =ChatInfo.objects.aggregate(Max('id')) last_id = id_max["id__max"] # print("后臺(tái)數(shù)據(jù)庫(kù)內(nèi)最新的id為", last_id) # 獲取請(qǐng)求的id值 old_last_id = wrappers.post(request, "last_id") print(old_last_id,"<-<-") print(old_last_id, type(old_last_id),"-->") # print("后臺(tái)發(fā)送過(guò)來(lái)的id為",old_last_id) # 返回的信息字典,返回當(dāng)前時(shí)間(current_date),返回信息列表(id_info) # 如果第一次請(qǐng)求,則回復(fù)最后一條消息的id if int(old_last_id) == 0: user_ip = wrappers.get_client_ip(request) result_dict = dict() result_dict["last_id"] = last_id result_dict["info"] = [{"id":"-->", "mess":"歡迎"+user_ip+"來(lái)到聊天室!", "user_name":"系統(tǒng)消息:"}] result_dict["user_id"] = "" result_dict = json.dumps(result_dict,ensure_ascii=False) # print("第一次握手") return JsonResponse({"data":result_dict}) # 如果數(shù)據(jù)內(nèi)沒(méi)有消息更新 elif int(old_last_id) >= int(last_id): result_dict = dict() result_dict["last_id"] = last_id result_dict["info"] = [{last_id:"歡迎再次來(lái)到聊天室!"}] result_dict["user_id"] = "" result_dict = json.dumps(result_dict,ensure_ascii=False) # print("一次無(wú)更新的交互") return JsonResponse({"data":result_dict}) # 如果有消息更新 else: # print("有更新的回復(fù)") result_dict = dict() # 獲取新的消息對(duì)象集合 the_new_info =ChatInfo.objects.filter(id__gt=old_last_id) # 創(chuàng)建消息列表 mess_list = list() # 將最新的消息組成字典進(jìn)行返回 for info in the_new_info: # print(info) # print ("-->",info.chat_content, info.id) # 創(chuàng)建消息字典 mess_dic = dict() mess_dic["id"] = info.id mess_dic["mess"] = info.chat_content # 將消息所屬的用戶(hù)添加到消息列表 mess_dic["user_name"] = info.user_name mess_dic["user_id"] = info.user_id # 將消息字典添加到消息列表 mess_list.append(mess_dic) result_dict["last_id"] = last_id result_dict["info"] = mess_list # result_dict["info"] = [{"id":3, "mess":"hahah"}, {"id":4, "mess":"666"}] result_dict = json.dumps(result_dict,ensure_ascii=False) # print("--->>>", type(result_dict)) return JsonResponse({"data":result_dict}) except: return JsonResponse({"ret":"刷新出現(xiàn)問(wèn)題"}) pass總結(jié)
以上所述是小編給大家介紹的Python使用django框架實(shí)現(xiàn)多人在線匿名聊天的小程序,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)VEVB武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選