Django websocket achieve complete real-time messaging, chat rooms, online customer service, etc.

What is a Websocket

WebSocket protocol is a full duplex communication over a single TCP connection

WebSocket enables exchange of data between the client and the server easier, allowing the server actively push data to the client. In the WebSocket API, the browser and the server only needs to complete a handshake, you can directly create a persistent connection between the two, and two-way data transmission

Now, many sites in order to achieve push technology, the technology used is polling. Polling is in a specific time interval (e.g., every 1 second), issues an HTTP request to the server by the browser, and returns the latest data to the client browser by the server. This traditional model brings obvious disadvantage that the browser requires constant request to the server, however, HTTP requests may contain a long head, which truly effective data may only be a small part, obviously this will waste a lot of bandwidth resources.
The relatively new technology to do the polling results are Comet. Although this technique can be two-way communication, but still need to issue a request repeatedly. And in Comet, the long link widely used, will consume server resources.

In this case, HTML5 WebSocket protocol is defined, better able to save server resources and bandwidth, and can be more real-time communication

Two Django achieve Websocket

django achieve websocket generally, there are two ways, one channels, one is dwebsocket. channels depends on the redis, twisted, etc., in contrast to the more convenient to use dwebsocket

Three dwebsocket installation

pip3 install dwebsocket

Four dwebsocket Configuration

Copy the code
= INSTALLED_APPS [ 
    ..... 
    ..... 
    'dwebsocket', 
] 
 
the MIDDLEWARE_CLASSES = [ 
    ...... 
    ...... 
    'dwebsocket.middleware.WebSocketMiddleware' # websocket to provide all of the URL, if only alone may not be selected from the view needs 
 
] 
WEBSOCKET_ACCEPT_ALL # = True may allow each individual practical view websockets
Copy the code
 

Five use

html code:

Copy the code
<! DOCTYPE HTML> 
<HTML lang = "EN"> 
<head> 
    <Meta charset = "UTF-. 8"> 
    <title> the Title </ title> 
</ head> 
<body> 


<Button the onclick = "WebSocketTest ()" > the Test </ the Button> 
</ body> 


<Script> 


    function WebSocketTest () { 
        Alert (1) 
        IF ( "the WebSocket" in window) { 
            Alert ( "your browser supports the WebSocket!"); 

            // open a web socket 
            = a WebSocket new new WS ( "WS: //127.0.0.1: 8000 / path /"); 

            ws.onopen = function () { 
                // is the Web on the Socket connection, use send () method for transmitting data 
                ws.send ( "Transmission data "); 
                Alert (" data transmission ... "); 
            };

            = function ws.onmessage (EVT) { 
                var received_msg = evt.data; 
                Alert ( "data has been received ..."); 
                Alert ( "Data:" + received_msg) 
            }; 

            ws.onclose = function () { 
                // Close the WebSocket 
                Alert ( "connection closed ..."); 
            }; 
        } 

        the else { 
            // browser does not support the WebSocket 
            Alert ( "your browser does not support the WebSocket!"); 
        } 
    } 


</ Script> 
</ HTML>
Copy the code

Layer view views:

Copy the code
from django.shortcuts import render,HttpResponse

# Create your views here.
def login(request):
    return render(request,'login.html')

from dwebsocket.decorators import accept_websocket
@accept_websocket
def path(request):
    if request.is_websocket():
        print(1)
        request.websocket.send('下载完成'.encode('utf-8'))
Copy the code

Routing layer:

Copy the code
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),
]
Copy the code
Copy the code
#dwebsocket two decorators: require_websocket and accept_websocekt, use require_websocket decorator will lead to the view function can not lead a normal http request is received, generally use accept_websocket way you can, and 
# 
number of built-in method # dwebsocket: 
# 
# request.is_websocket (): determining whether the request is websocket way, return true, otherwise returns to false 
# request.websocket: websocket when the request for the time, will increase in a websocket attribute request, 
# WebSocket.wait () returns the one sent by the client message not received message will cause blocking 
# WebSocket.read () and wait and they can receive messages returned, but this is non-blocking, no message is returned None 
# WebSocket.count_messages () returns the message number 
# WebSocket.has_messages () returns whether there is a new message over 
# WebSocket.send (message) as the client sends a message, message types to byte
Copy the code

Guess you like

Origin www.cnblogs.com/ellisonzhang/p/11229293.html