目录
websocket 方法总结
群聊功能
基于 websocket 聊天室 (版本一)
websocket 方法总结
- # 后端 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
基于 websocket 聊天室 (版本一)
routing.py
- 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.html
- <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>
来源: http://www.bubuko.com/infodetail-3506851.html