# 后端 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>