zoukankan      html  css  js  c++  java
  • Django websocket 长连接使用

    下载  pip install dwebsocket

     

    WebSocket是一种在单个TCP连接上进行全双工通信的协议

    WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输

    现在,很多网站为了实现推送技术,所用的技术都是轮询。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP请求,然后由服务器返回最新的数据给客户端的浏览器。这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。

    而比较新的技术去做轮询的效果是Comet。这种技术虽然可以双向通信,但依然需要反复发出请求。而且在Comet中,普遍采用的长链接,也会消耗服务器资源。

    在这种情况下,HTML5定义了WebSocket协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯

    1. http协议是用在应用层的协议,他是基于tcp协议的,http协议建立链接也必须要有三次握手才能发送信息。

      http链接分为短链接,长链接,短链接是每次请求都要三次握手才能发送自己的信息。即每一个request对应一个response。长链接是在一定的期限内保持链接。保持TCP连接不断开。客户端与服务器通信,必须要有客户端发起然后服务器返回结果。客户端是主动的,服务器是被动的。

    2. WebSocket 

      WebSocket他是为了解决客户端发起多个http请求到服务器资源浏览器必须要经过长时间的轮训问题而生的,他实现了多路复用,他是全双工通信。在webSocket协议下客服端和浏览器可以同时发送信息。

    建立了WenSocket之后服务器不必在浏览器发送request请求之后才能发送信息到浏览器。这时的服务器已有主动权想什么时候发就可以发送信息到服务器。而且信息当中不必在带有head的部分信息了与http的长链接通信来说,这种方式,不仅能降低服务器的压力。而且信息当中也减少了部分多余的信息。

    视图文件 向前端发送数据

    from dwebsocket.decorators import accept_websocket
    @accept_websocket
    def test_websocket(request):
        if request.is_websocket():
            while 1:
                time.sleep(1) ## 向前端发送时间
                dit = {
                    'time':time.strftime('%Y.%m.%d %H:%M:%S',time.localtime(time.time()))
                }
                request.websocket.send(json.dumps(dit))

    视图文件 接收前端发送过来的数据

    #接受前端信息
    @accept_websocket
    def test_socket(request):
        if request.is_websocket():
            for message in request.websocket:
                print(message)
                request.websocket.send(message)

    路由文件

    from .views import test_socket,test_websocket
    
    
    urlpatterns = [
        path('test_socket',test_socket),
        path('test_websocket',test_websocket),
    
    ]

    前端连接 接收后端给予数据

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8"/>
        <title>Chat Room</title>
    </head>
    <body>
    </body>
    <script>
       
       //生成socket对象
       var socket = new WebSocket("ws:" + window.location.host + "/md_admin/test_websocket");
    
    
                socket.onopen = function () {
                    console.log('WebSocket open');//成功连接上Websocket
                };
                socket.onmessage = function (e) {
                    console.log('message: ' + e.data);//打印服务端返回的数据
                };
                socket.onclose=function(e){
                  console.log(e);
                  socket.close(); //关闭TCP连接
                };
                if (socket.readyState == WebSocket.OPEN){
                socket.onopen();
                }
        
    </script>
    </html>

    前端连接 向后端发送数据

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8"/>
        <title>Chat Room</title>
    </head>
    <body>
        <input id="chat-message-input" type="text" size="100"/><br/>
        <input id="chat-message-submit" type="button" value="Send" onclick='sendmessage()'/>
    </body>
    <script>
       
       //生成socket对象
       var socket = new WebSocket("ws:" + window.location.host + "/md_admin/test_socket");
    
    
                socket.onopen = function () {
                    console.log('WebSocket open');//成功连接上Websocket
                };
                socket.onmessage = function (e) {
                    console.log('message: ' + e.data);//打印服务端返回的数据
                };
                socket.onclose=function(e){
                  console.log(e);
                  socket.close(); //关闭TCP连接
                };
                if (socket.readyState == WebSocket.OPEN){
                socket.onopen();
                }
    
                window.s = socket;
    
    function sendmessage(){
    
        window.s.send(document.getElementById("chat-message-input").value);
    
    }
    
        
    </script>
    </html>
  • 相关阅读:
    jdk-8u271-windows-x64
    wps 2019 专业版最新激活密匙
    未分页内存泄露
    Nonpaged Pool(未分页池)占用内存过多分析定位
    python异常处理
    如何开发在线考试系统
    kvm学习
    MySQL安全审计-等保2.0
    Linux下启动/关闭Oracle
    rocketmq systemctl 启动
  • 原文地址:https://www.cnblogs.com/Niuxingyu/p/10760338.html
Copyright © 2011-2022 走看看