https://channels.readthedocs.io/en/latest/tutorial/part_1.html
不同于HTTP请求,WebSockets协议使用双向直接通信,也就是说不需要客户端发送请求,服务器端就可以向发送数据。HTTP协议中,只有客户端可以发送请求和接收响应,WebSockets协议中,服务器端可以同时与多个客户端进行通信。我们将使用ws://前缀而不是http://
ModuleNotFoundError: No module named 'win32api'
安装
pip install channels
使用(Integrate the Channels library 集成)
First, you should add channels
to your INSTALLED_APPS
setting
Then, make a default routing in myproject/routing.py()
from channels.routing import ProtocolTypeRouter application = ProtocolTypeRouter({ # Empty for now (http->django views is added by default) })
ASGI_APPLICATION
setting to point to that routing object as your root application:
ASGI_APPLICATION = "myproject.routing.application"
Once enabled, channels
will integrate itself into Django and take control of the runserver。
应用
表单文件,视图处理文件
routing.py文件其实就是个表单,功能和Django原来的urls.py文件一样,不过这里使用的不是URL,而是请求的类型。
from channels.routing import route from channels_example import consumers #导入处理函数 channel_routing = [ #route("http.request", consumers.http_consumer), 这个表项比较特殊,他响应的是http.request,也就是说有HTTP请求时就会响应,同时urls.py里面的表单会失效 route("websocket.connect", consumers.ws_connect), #当WebSocket请求连接上时调用consumers.ws_connect函数 route("websocket.receive", consumers.ws_message), #当WebSocket请求发来消息时。。。 route("websocket.disconnect", consumers.ws_disconnect), #当WebSocket请求断开连接时。。。 ]
consumers.py就相当于新的view.py。
from django.http import HttpResponse from channels.handler import AsgiHandler #message.reply_channel 一个客户端通道的对象 #message.reply_channel.send(chunk) 用来唯一返回这个客户端 #一个管道大概会持续30s #当连接上时,发回去一个connect字符串 def ws_connect(message): message.reply_channel.send({"connect"}) #将发来的信息原样返回 def ws_message(message): message.reply_channel.send({ "text": message.content['text'], }) #断开连接时发送一个disconnect字符串,当然,他已经收不到了 def ws_disconnect(message): message.reply_channel.send({"disconnect"})
通道层:
CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, "ROUTING": "chat.routing.channel_routing", }, }
需要注意的是 ROUTING 参数,他是用来指定WebSocket表单的位置,当有WebSocket请求访问时,就会根据这个路径找到相应表单,调用相应的函数进行处理。
channels_example.routing 就是我们刚才建好的routing,py文件,里面的channel_routing是我的处理函数。