# 後端 3個 class ChatConsumer(WebsocketConsumer): def websocket_connect(self, message): """客戶端請求創建連接時 自動觸發""" self.accept() # 創建連接 而且自動幫你維護每個客戶端 def websocket_receive(self, message): """客戶端發送數據過來 自動觸發""" # print(message) # message = {'type': 'websocket.receive', 'text': 'hello world!'} text = message.get('text') # 真正的數據 # 給客戶端發送消息 self.send(text_data='介紹女友') def websocket_disconnect(self, message): """客戶端斷開連接以後 自動觸發""" raise StopConsumer() # 前端 4個 var ws = new WebSocket('ws://127.0.0.1:8000/home/'); // 1 握手環節驗證成功以後 自動觸發 onopen ws.onopen = function () { console.log('握手成功') } // 2 給服務端發送消息 send function sendMsg() { ws.send($('#txt').val()) } // 3 一旦服務端有消息 自動觸發 onmessage ws.onmessage = function (args) { // console.log(args) // args是一個對象 // 獲取發送的數據 console.log(args.data) } // 4 斷開連接以後 自動觸發 onclose ws.onclose = function () { ws.close() }
咱們是經過本身維護一個列表存儲連接對象的方式完成了簡易版本的羣聊 其實channels給你提供了一個用於作羣聊的模塊,該模塊能夠實現真正的分組聊天 該模塊就是channel-layers
routing.pyhtml
from channels.routing import ProtocolTypeRouter,URLRouter from django.conf.urls import url from app01 import consumers application = ProtocolTypeRouter({ 'websocket':URLRouter([ # 書寫websocket路由與視圖函數對應關係 url(r'^home/',consumers.ChatConsumer) ]) })
consumers.py前端
from channels.exceptions import StopConsumer from channels.generic.websocket import WebsocketConsumer consumer_object_list = [] class ChatConsumer(WebsocketConsumer): def websocket_connect(self, message): """客戶端請求創建連接時 自動觸發""" self.accept() # 創建連接 而且自動幫你維護每個客戶端 consumer_object_list.append(self) # 來一個用戶添加到列表中 def websocket_receive(self, message): """客戶端發送數據過來 自動觸發""" # print(message) # message = {'type': 'websocket.receive', 'text': 'hello world!'} text = message.get('text') # 真正的數據 # 循環給每個客戶端發送消息,模擬同步 for obj in consumer_object_list: obj.send(text_data=text) def websocket_disconnect(self, message): """客戶端斷開連接以後 自動觸發""" consumer_object_list.remove(self) raise StopConsumer()
home.htmlpython
<body> <h1>聊天室</h1> <input type="text" id="txt"> <button onclick="sendMsg()">發送</button> # 綁定事件 <h1>聊天記錄</h1> <div class="record"></div> <script> # 幫咱們自動完成握手環節 var ws = new WebSocket('ws://127.0.0.1:8000/home/'); // 1 握手環節驗證成功以後 自動觸發 onopen ws.onopen = function () { console.log('握手成功') } // 2 給服務端發送消息 send function sendMsg() { ws.send($('#txt').val()) } // 3 一旦服務端有消息 自動觸發 onmessage ws.onmessage = function (args) { // console.log(args) // args是一個對象 // 獲取發送的數據 // 1 建立p標籤 var pEle = $('<p>'); pEle.text(args.data); # 獲取後端傳過來的數據,並放進p標籤 $('.record').append(pEle) # 添加p標籤 } // 4 斷開連接以後 自動觸發 onclose ws.onclose = function () { ws.close() } </script> </body>