WebSocket协议是基于TCP的一种新的协议。WebSocket最初在HTML5规范中被引用为TCP连接,作为基于TCP的套接字API的占位符。它实现了浏览器与服务器全双工(full-duplex)通信。其本质是保持TCP连接,在浏览器和服务端通过Socket进行通信。
django 使用websocket需要
pip3 install channels==2.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01.apps.App01Config', # 项目中要使用channels做websocket了. "channels", ]
本质: channels会把原来只支持http协议的wsgi,换成支持http和websocket协议的asgi
配置application
# settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01.apps.App01Config', # 项目中要使用channels做websocket了. "channels", ] ASGI_APPLICATION = "channel_demo.routing.application"
# channel_demo/routing.py(新建routing.py文件)
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from app01 import consumers
application = ProtocolTypeRouter({
'websocket': URLRouter([
url(r'^chat/$', consumers.ChatConsumer),
])
})
app下建立consumers文件
from channels.generic.websocket import WebsocketConsumer from channels.exceptions import StopConsumer CONSUMER_OBJECT_LIST = [] class ChatConsumer(WebsocketConsumer): def websocket_connect(self, message): """ 客户端发来连接请求之后就会被触发 :param message: :return: """ # 服务端接收连接,向客户端浏览器发送一个加密字符串 self.accept() # 连接成功 CONSUMER_OBJECT_LIST.append(self) def websocket_receive(self, message): """ 客户端浏览器向服务端发送消息,此方法自动触发 :param message: :return: """ # 服务端给客户端回一条消息 # self.send(text_data=message['text']) for obj in CONSUMER_OBJECT_LIST: obj.send(text_data=message['text']) def websocket_disconnect(self, message): """ 客户端主动断开连接 :param message: :return: """ # 服务端断开连接 CONSUMER_OBJECT_LIST.remove(self) raise StopConsumer()
web聊天室HTML样例,用ajax实现
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>欢迎进入Channels聊天室</h1> <div> <input type="text" id="txt" placeholder="请输入"> <input type="button" onclick="sendMsg();" value="发送"> <input type="button" onclick="close();" value="断开连接"> </div> <div> <h3>聊天记录</h3> <div id="content"></div> </div> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script> var ws = new WebSocket("ws://127.0.0.1:8000/chat/"); ws.onopen = function(){ //客户端在握手环节验证成功之后,自动执行此方法. console.log('连接成功'); }; ws.onmessage = function (event) { var tag = $('<div>'); tag.text(event.data); $('#content').append(tag); }; function sendMsg() { ws.send($('#txt').val()); } function close() { ws.close(); } </script> </body> </html>