Detailed explanation of using Websockets in Django
1. Introduction to Websockets
With the development of the Internet, the traditional HTTP protocol has been difficult to meet the increasingly complex needs of Web applications. In recent years, with the birth of HTML5, the WebSocket protocol was proposed, which realizes full-duplex communication between the browser and the server, expands the communication functions between the browser and the server, and enables the server to actively send data to the client.
We know that the traditional HTTP protocol is stateless. Each request (request) must be actively initiated by the client (such as a browser). The server returns the response result after processing, and it is difficult for the server to actively request The client sends data; this traditional Web model in which the client is the active party and the server is the passive party causes less trouble for Web applications where information changes infrequently, but it brings problems to Web applications involving real-time information. A big inconvenience, such as applications with instant messaging, real-time data, subscription push and other functions. Before the WebSocket specification was proposed, developers often used compromise solutions to implement these real-time functions: polling and Comet technologies. In fact, the latter is essentially a kind of polling, but it has been improved.
Polling is the original solution for implementing real-time web applications. Polling technology requires the client to periodically send requests to the server at set intervals and frequently query whether there are new data changes. Obviously, this approach will result in too many unnecessary requests, wasting traffic and server resources.
Comet technology can be divided into long polling and streaming technology. Long polling improves the above polling technology and reduces useless requests. It sets an expiration time for certain data, and sends a request to the server only when the data expires; this mechanism is suitable for situations where data changes are not particularly frequent. Streaming technology usually means that the client uses a hidden window to establish a long HTTP connection with the server. The server will continuously update the connection status to keep the HTTP long connection alive; in this case, the server can actively transfer data through this long connection. Sent to the client; streaming technology may test the performance of the server in a large concurrency environment.
These two technologies are based on the request-response model, and they are not real-time technologies in the true sense; each of their requests and responses wastes a certain amount of traffic on the same header information, and the development complexity Also larger.
Along with the launch of HTML5, WebSocket truly realizes real-time communication on the Web, enabling the B/S mode to have the real-time communication capabilities of the C/S mode. The workflow of WebSocket is as follows: the browser sends a request to the server to establish a WebSocket connection through JavaScript. After the WebSocket connection is successfully established, the client and server can transmit data through the TCP connection. Because the WebSocket connection is essentially a TCP connection, it does not need to carry repeated header data with each transmission, so its data transmission volume is much smaller than polling and Comet technologies.
2. Install dwebsocket
Installation method:
1. Through pip
pip install dwebsocket2
2. By downloading to local
Execute python setup.py install
Attachment: If the installation fails and prompts about the ASCII code, just delete the content in the readme
3. How to use
If If you want to handle a websocket connection for a separate view you can use the accept_websocket decorator, which will route standard HTTP requests to the view. Using the require_websocke decorator only allows WebSocket connections and will reject normal HTTP requests.
Add the setting MIDDLEWARE_CLASSES=dwebsocket.middleware.WebSocketMiddlewareThis will deny the use of separate views websocket, you must add accept_websocket decoration device.
SettingWEBSOCKET_ACCEPT_ALL=TrueAllows each individual view to be usefulwebsockets
Some methods and properties
1.request.is_websocket()
#If it is a websocket request, it returns True, if it is an ordinary http request, it returns False. You can use this method to distinguish them. .
2.request.websocket
在一个websocket请求建立之后,这个请求将会有一个websocket属性,用来给客户端提供一个简单的api通讯,如果request.is_websocket()是False,这个属性将是None。
3.WebSocket.wait()
返回一个客户端发送的信息,在客户端关闭连接之前他不会返回任何值,这种情况下,方法将返回None
4.WebSocket.read()
如果没有从客户端接收到新的消息,read方法会返回一个新的消息,如果没有,就不返回。这是一个替代wait的非阻塞方法
5.WebSocket.count_messages()
返回消息队列数量
6.WebSocket.has_messages()
如果有新消息返回True,否则返回False
7.WebSocket.send(message)
向客户端发送消息
8.WebSocket.__iter__()
websocket迭代器
四、干货
功能:让我们从客户端接收一条消息,将该消息发送回客户端并关闭连接。
1.新建一个django项目
2.新建index.html在templates文件夹下,编写我们的客户端
<!DOCTYPE html> <html> <head> <title>django-websocket</title> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script type="text/javascript">//<![CDATA[ $(function () { $('#send_message').click(function () { var socket = new WebSocket("ws://" + window.location.host + "/echo_once"); socket.onopen = function () { console.log('WebSocket open');//成功连接上Websocket socket.send($('#message').val());//发送数据到服务端 }; socket.onmessage = function (e) { console.log('message: ' + e.data);//打印服务端返回的数据 $('#messagecontainer').prepend('<p>' + e.data + '</p>'); }; }); }); //]]></script> </head> <body> <br> <input type="text" id="message" value="Hello, World!"/> <button type="button" id="send_message">发送 message</button> <h1 id="Received-nbsp-Messages">Received Messages</h1> <div id="messagecontainer"> </div> </body> </html>
3.app的views.py编写我们的服务端
from dwebsocket import require_websocket @require_websocketdef echo_once(request): message = request.websocket.wait() request.websocket.send(message)
4.url路由设置
from demo import views as v urlpatterns = [ url(r'^index/', v.index), url(r'^echo_once', v.echo_once), ]
5.runserver运行,效果展示
可以看到,当我们点击按钮之后,服务端发送消息到客户端之后,就自动关闭了连接。
当然,我们也可以让服务端不自动关闭连接,接下来利用websocket和http Get写一个一样的功能的函数,
6.新建一个html,写一个新的客户端
<!DOCTYPE html> <html> <head> <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() } /*创建socket连接*/ var socket = new WebSocket("ws://" + window.location.host + "/echo"); socket.onopen = function () { console.log('WebSocket open');//成功连接上Websocket }; socket.onmessage = function (e) { console.log('message: ' + e.data);//打印出服务端返回过来的数据 $('#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 () { //如果未连接到websocket if (!window.s) { alert("websocket未连接."); } else { window.s.send($('#message').val());//通过websocket发送数据 } }); $('#close_websocket').click(function () { if (window.s) { window.s.close();//关闭websocket console.log('websocket已关闭'); } }); }); //]]></script> </head> <body> <br> <input type="text" id="message" value="Hello, World!"/> <button type="button" id="connect_websocket">连接 websocket</button> <button type="button" id="send_message">发送 message</button> <button type="button" id="close_websocket">关闭 websocket</button> <h1 id="Received-nbsp-Messages">Received Messages</h1> <div id="messagecontainer"> </div> </body> </html>
7.在viws.py中加入新的方法
from django.shortcuts import render from dwebsocket.decorators import accept_websocket,require_websocket from django.http import HttpResponse @accept_websocket def echo(request): if not request.is_websocket():#判断是不是websocket连接 try:#如果是普通的http方法 message = request.GET['message'] return HttpResponse(message) except: return render(request,'index.html') else: for message in request.websocket: request.websocket.send(message)#发送消息到客户端
8.url.py
from demo import views as v urlpatterns = [ url(r'^index2/', v.index2), url(r'^echo$', v.echo), ]
9.runserver运行,看看效果
可以看到,只有当我们手动关闭连接时候,websocket才会关闭。
The above is the detailed content of Detailed explanation of using Websockets in Django. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code
