http协议websocket协议
-
http协议,一次请求一次响应。
-
websocket 协议,创建持久的连接不断开,基于这个连接可以进行手法数据(服务器可以主动像客户端发送数据)
-
web聊天室
-
实时图标,柱状图,饼图。
-
websocket 原理
-
连接,客户端发起
-
握手验证,客户端发送消息,后端接收到消息在做一些特殊处理并且返回
-
客户端发送随机字符串
-
服务端接收,加上magic string 拼接,进行hmac1加密,在base64编码返回给前端
-
前端接收加密的密文,进行验证。
-
-
收发数据
-
先获取第二个字节 8 位 10001010
-
再获取第二个字节的后七位 0001010
-
=127 , 2个字节,8个字节, 其他字节(4个字节masking key + 数据)
-
=126, 2个字节,2个字节 其他字节(4个字节masking key + 数据)
-
《=125 ,2字节 其他字节(4个字节masking key + 数据)
-
获取masking key 然后对数据进行解密。
-
-
-
断开连接
django框架
djano默认不支持websocket ,需要安装组件
pip install channels
配置
1.注册app
注意事项
-
django == 4.2.7
-
channels == 4.0.0
-
此版本需要注册app的时候将 daphne 放到最前面否则不能以asgi 的方式启动服务
INSTALLED_APPS = [
'daphne',
'channels',
]
2.在setting 中添加 ASGI_APPLICATION = ‘websocket.asgi.application’
ASGI_APPLICATION = 'websocket.asgi.application'
3.修改asgi 文件
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from . import routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket.settings')
#application = get_asgi_application()
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": URLRouter(routing.websocket_urlpatterns)
})
4.setting 文件同级目录创建 routing 文件
from django.urls import re_path
from app01 import consumers
websocket_urlpatterns = [
re_path(r'ws/(?P<group>\w+)/$', consumers.ChatConsumer.as_asgi()),
]
5.app01目录下创建consumers.py , 编写处理websocket 业务逻辑
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
def websocket_receive(self, message):
# 浏览器基于websocket向后端发送数据,自动触发接收消息。
print(message)
self.send("不要回复不要回复")
# self.close()
def websocket_disconnect(self, message):
# 客户端与服务端断开连接时,自动触发。
print("断开连接")
raise StopConsumer()