WebSocket's Django Simple to use

Source: Internet
Author: User
Tags button type

WebSocket Protocol:

WebSocket protocol is a new protocol for HTML5. It is the implementation of browser-to-server full-duplex communication (Full-duplex). HTML5 defines the WebSocket protocol to better conserve server resources and bandwidth and to achieve real-time communication.
We know that the traditional HTTP protocol is stateless, each request must be initiated by the client (such as a browser), the server to return response results after processing, and the service side is very difficult to actively send data to the client, the client is the active side, The traditional Web mode with the passive side of the server is less troublesome for Web applications where information is not changing frequently, but it is inconvenient for Web applications involving real-time information, such as applications with instant messaging, real-time data, and subscription push. Before the WebSocket specification was introduced, developers would often use a compromise solution: polling (polling) and comet technology to achieve these real-time features. In fact, the latter is also a kind of polling, but some improvement.
Polling is the most primitive solution for implementing real-time Web applications. Polling technology requires clients to periodically send requests to the server at set intervals, frequently querying for new data changes. Obviously, this approach leads to excessive unnecessary requests, wasteful traffic, and server resources.
Comet technology can also be divided into long polling and streaming technology. Long polling improves the polling technology mentioned above, reducing useless requests. It sets the expiration time for some data and sends the request to the server when the data expires, a mechanism suitable for data changes that are not particularly frequent. Streaming technology usually refers to the client using a hidden window and the server to establish an HTTP long connection, the server will constantly update the connection state to keep the HTTP long connection to survive, so that the server can use this long connection to actively send data to the client; streaming technology in a large concurrency environment, May test performance on the server side.
Both of these technologies are based on the request-response model, which is not really real-time technology; Each request and response wastes a certain amount of traffic on the same header information, and the complexity of the development is greater.
With the launch of the HTML5 WebSocket, the real real-time communication of the web, so that b/s model with the C/s mode of real-time communication capabilities. WebSocket Workflow is this: the browser through JavaScript to the server to establish a WebSocket connection request, after the WebSocket connection is established successfully, the client and the server can transfer data over a TCP connection. Because the WebSocket connection is essentially a TCP connection and does not require duplicate header data per transmission, it has a much smaller data transfer than polling and comet technology.

WebSocket
The WebSocket protocol supports full-duplex communication between a client (running untrusted code in a controlled environment) and a remote host (who chooses to join the code)
During the implementation of the WebSocket connection, the WebSocket connection request is made via the browser, and then the server responds, which is often referred to as a "handshake". In the WebSocket API, the browser and server only need to do a handshake, and then a fast channel is formed between the browser and the server. The data can be transmitted to each other directly between the two. In this WebSocket agreement, there are two major benefits to our instant service:
1. Header
The header to communicate with each other is very small-about 2 Bytes
2. Server Push
Server push, the server no longer passively receives the browser's request to return the data, but is actively pushed to the browser when there is new data.

The above contents refer to a variety of Baidu results summary.

Example: Using Dwebsocket to use WebSocket in Django
1. First install the Django plugin Dwebsocket,pip install Dwebsocket
2, write the client and server code
Client:
<! DOCTYPE html>
<title>django-websocket</title>
<script src= "Http://code.jquery.com/jquery-1.11.1.min.js" ></script>
<script type= "Text/javascript" >//<! [cdata[
$ (function () {
$ (' #connect_websocket '). Click (function () {
if (WINDOW.S) {
Window.s.close ()
}
/* Create a socket connection */
var socket = new WebSocket ("ws://" + ' 127.0.0.1:8000 ' + "/app02/echo/");
Socket.onopen = function () {
Console.log (' WebSocket open ');//successfully connected on WebSocket
};
Socket.onmessage = function (e) {
Console.log (' message: ' + e.data);//print out the data returned from the server
$ (' #messagecontainer '). Prepend (' <p> ' + e.data + ' </p> ');
};
Call OnOpen directly if socket is already open
if (socket.readystate = = Websocket.open) Socket.onopen ();
WINDOW.S = socket;
});
$ (' #send_message '). Click (function () {
If you are not connected to WebSocket
if (!WINDOW.S) {
Alert ("WebSocket not connected.");
} else {
Window.s.send ($ (' #message '). Val ());//Send data via WebSocket
}
});
$ (' #close_websocket '). Click (function () {
if (WINDOW.S) {
Window.s.close ();//Close WebSocket
Console.log (' WebSocket closed ');
}
});

});
]]></script>
<body>
<br>
<input type= "text" id= "message" value= "Hello, world!" />
<button type= "button" id= "Connect_websocket" > Connection websocket</button>
<button type= "button" id= "Send_message" > Send message</button>
<button type= "button" id= "Close_websocket" > Close websocket</button>
<div id= "Messagecontainer" >

</div>
</body>

Server-side:
urls.py
#-*-Coding:ut
Urlpatterns = [
URL (r ' ^home/', views.home),
URL (r ' ^websocket/', views.websocket_test),
URL (r ' ^echo/', Views.echo),
]
views.py
#-*-Coding:utf-8-*-
From Dwebsocket import Require_websocket,accept_websocket
Import Dwebsocket

@require_websocket #只接受websocket请求, do not accept HTTP requests, this is the adorner that called Dwebsocket
def websocket_test (Request):
message = Request.websocket.wait ()
Request.websocket.send (Message)

@accept_websocket #既能接受http也能接受websocket请求
def Echo (Request):
If not Request.is_websocket ():
Try
message = Request. get[' message ']
return HttpResponse (Message)
Except
return render (Request, ' app02/user2.html ')
Else
For message in Request.websocket:
Print message
Request.websocket.send (message + ' This is your hair ... '. Encode (' Utf-8 '))
3. Here are some methods and properties
1.request.is_websocket ()

If a websocket request returns true, it can be distinguished by this method if it is a normal HTTP request that returns FALSE.

2.request.websocket

After a websocket request is established, the request will have a WebSocket attribute to provide a simple API communication to the client, and if Request.is_websocket () is false, this property will be none.

3.websocket.wait ()

Returns a message sent by a client that does not return any value until the client closes the connection, in which case the method returns none

4.websocket.read ()

If no new messages are received from the client, the Read method returns a new message, and if it does not, it is not returned. This is a non-blocking method that replaces wait

5.websocket.count_messages ()

Returns the number of message queues

6.websocket.has_messages ()

Returns False if a new message returns True

7.websocket.send (Message)

Send a message to the client

8.WEBSOCKET.__ITER__ ()

WebSocket iterators

Reference Link: https://www.cnblogs.com/huguodong/p/6611602.html,http://blog.csdn.net/linxi7/article/details/76161584

WebSocket's Django Simple to use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.