django achieve websocket generally, there are two ways, one channels, one is dwebsocket. channels depends on redis, twisted, etc.
A dwebsocket
1 Django achieve Websocket
django achieve websocket generally, there are two ways, one channels, one is dwebsocket. channels depends on the redis, twisted, etc., compared to use dwebsocket to be more convenient for some
2 dwebsocket installation
pip3 install dwebsocket
3 dwebsocket Configuration
setting setting
INSTALLED_APPS = [ ... ... ' Dwebsocket ' ]
import dwebsocket The MIDDLEWARE_CLASSES = [ ' dwebsocket.middleware.WebSocketMiddleware ' # all URL websocket to provide, if necessary, only a single view is not selected ] WEBSOCKET_ACCEPT_ALL = True # may allow each individual practical view websockets
urls.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', views.login), url(r'^path/', views.path), ]
views.py
from django.shortcuts import render def login(request): return render(request, 'index.html') from dwebsocket.decorators import accept_websocket @accept_websocket def path(request): if request.is_websocket(): print(1) request.websocket.send ( ' download completes ' .encode ( ' UTF-. 8 ' ))
html
<body> <button onclick="WebSocketTest()">test</button> </body> <script> function WebSocketTest() { if ("WebSocket" in window) { Alert ( " Your browser supports the WebSocket! " ); // Open a web socket var ws = new WebSocket("ws://127.0.0.1:8000/path/"); console.log('ws',ws) ws.onopen = function () { // the Web is the Socket connection, using the send () method for transmitting data ws.send ( " transmit data " ); Alert ( " data transmission ... " ); }; ws.onmessage = function (evt) { var received_msg = evt.data; Alert ( " data has been received ... " ); Alert ( " Data: " + received_msg) }; ws.onclose = function () { // 关闭 websocket Alert ( " Connection closed ... " ); }; } the else { // browser does not support WebSocket Alert ( " Your browser does not support the WebSocket! " ); } } </script>
4 dwesocket parameters
dwebsocket two decorators: require_websocket and accept_websocekt, using require_websocket decorative function will not result in view of the results in a normal http request received, generally used accept_websocket embodiment can,
dwebsocket some built-in methods:
request.websocket (): when the request is websocket time, increases in a websocket attribute request, WebSocket.wait (): Returns the client sends a message, it will not receive any information leading to obstruction WebSocket.read () and wait message returned as acceptable, but this is non-blocking, no message return None WebSocket.count_messages (): Return the number of messages WebSocket.has_messages (): Returns whether there is new information coming WebSocket.send (msg): Like the client sends a message, message type byte is |
二 channels