How to use Websockets in Django

Source: Internet
Author: User
With the development of the Internet, the traditional HTTP protocol has been difficult to meet the increasingly complex requirements of Web applications. In recent years, with the advent of HTML5, the WebSocket protocol has been proposed, which enables full-duplex communication between browsers and servers, and extends the communication between browsers and servers, this allows the server to actively send data to the client. We know that the traditional HTTP protocol is stateless, and each request must be actively initiated by a client (such as a browser). after the server processes the request, the response result is returned, however, it is difficult for the server to actively send data to the client. the client is the active party, and the server is the passive party. traditional Web mode for Web 1. Introduction to Websockets

With the development of the Internet, the traditional HTTP protocol has been difficult to meet the increasingly complex requirements of Web applications. In recent years, with the advent of HTML5, the WebSocket protocol has been proposed, which enables full-duplex communication between browsers and servers, and extends the communication between browsers and servers, this allows the server to actively send data to the client.
We know that the traditional HTTP protocol is stateless, and each request must be actively initiated by a client (such as a browser). after the server processes the request, the response result is returned, however, it is difficult for the server to actively send data to the client. This client is the active party, and the server is the passive party. the traditional Web mode causes less trouble for Web applications with less frequent information changes, however, it is inconvenient for Web applications involving real-time information, such as applications with instant messaging, real-time data, subscription push, and other functions. Before the WebSocket specification is proposed, developers often use the compromise solution to implement these functions with strong real-time performance: polling and Comet technologies. In fact, the latter is essentially a kind of round robin, but it is only improved.
Round Robin is the most primitive solution for implementing real-time Web applications. The polling technology requires the client to periodically send requests to the server at a specified interval and frequently query for new data changes. Obviously, this method will cause too many unnecessary requests and waste traffic and server resources.
The Comet technology can also be divided into long polling and stream technologies. Long polling improves the polling technology and reduces useless requests. It sets the expiration time for some data and sends requests to the server only after the data expires. this mechanism is suitable for situations where data changes are not very frequent. Stream technology usually means that the client uses a hidden window to establish an HTTP persistent connection with the server, and the server constantly updates the connection status to keep the HTTP persistent connection alive. in this way, the server can actively send data to the client through this persistent connection. streaming technology may test the performance of the server in a large concurrency environment.
Both of these technologies are based on the request-response mode, which is not real-time, A certain amount of traffic is wasted on the same header information, and the development complexity is also large.
Along with the WebSocket launched by HTML5, the real-time Web communication is realized, and the B/S mode has the real-time communication capability of the C/S mode. The WebSocket workflow is like this: the browser sends a WebSocket connection request to the server through JavaScript. after the WebSocket connection is established successfully, the client and the server can transmit data through the TCP connection. Because the WebSocket connection is essentially a TCP connection and does not require repeated header data to be carried during each transmission, the data transmission volume is much smaller than the polling and Comet technologies.

II. installation of dwebsocket:

1. pip

pip install  dwebsocket2

2. download to local

Decompress and run python setup. py install.

Note: if the installation fails, you can simply delete the content in readme with the ASCII code.

III. usage

If you want to process a websocklet connection for a separate view, you can use the accept_websocket decorator, which routes standard HTTP requests to the view. Using the require_websocke decorator only allows WebSocket connection, and rejects normal HTTP requests.

Add the MIDDLEWARE_CLASSES = dwebsocket. middleware. WebSocketMiddleware in the settings. in this case, the view utility websocket is denied and the accept_websocket modifier must be added.

Set WEBSOCKET_ACCEPT_ALL = True to allow each independent view to use websockets.

Some methods and attributes 1.request.is_websocket()

If a websocket request returns True, if a common http request returns False, you can use this method to distinguish them.

2.request.websocket

After a websocket request is created, the request will have a websocket attribute to provide a simple api communication for the client. ifRequest. is_websocket () is False. this attribute will be None.

3.WebSocket.wait()

Returns the information sent by a client. no value is returned before the client closes the connection. in this case, the method returns None.

4.WebSocket.read()

If a new message is not received from the client, the read method returns a new message. if not, no new message is returned. This is a non-blocking method to replace wait.

5.WebSocket.count_messages()

Number of returned message queues

6.WebSocket.has_messages()

Returns True if a new message exists. otherwise, returns False.

7.WebSocket.send(message)

Send messages to clients

8.WebSocket.__iter__()

Websocket iterator

4. Dry Goods

Function: Let's receive a message from the client, send the message back to the client, and close the connection.

1. create a django project

2.create index.html in the templates folder and write our client

    Django-websocket    

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.