Django中使用websocket


Django中使用websocket

pip install dwebsocket

settings.py中的配置

INSTALLED_APPS = [
    .....
    .....
    'dwebsocket',
]
 
MIDDLEWARE_CLASSES = [
    ......
    ......
    'dwebsocket.middleware.WebSocketMiddleware'  # 為所有的URL提供websocket,如果只是單獨的視圖需要可以不選
 
]
WEBSOCKET_ACCEPT_ALL=True   # 可以允許每一個單獨的視圖實用websockets

views.py中使用

...
from dwebsocket.decorators import accept_websocket

# @login_required
@accept_websocket
def dashboard(request):
    return DashboardHandler(request).response()


class DashboardHandler(BaseHandler):
    def __init__(self, request):
        super(DashboardHandler, self).__init__(request)

    def page(self, x):
        try:
            if self.request.is_websocket():
                # start do check clients
                count = 0
                while True:
                    count += 10
                    time.sleep(2)
                    self.request.websocket.send(('%s%%' % count).encode('utf-8'))
                    if count == 100:
                        break
            else:
                return render(self.request, 'engine/admin/main.html')
        except Exception as err:
            logger.exception(err)

在index.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 () {
        $('#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>Received Messages</h1>
<div id="messagecontainer">
 
</div>
</body>
</html>

wss: Error during WebSocket handshake: Unexpected response code: 200報錯

修改nginx的配置文件即可

對我來說,解決方法是設置以下響應標頭:“主機”,“連接”和“升級”。對於nginx情況(socket.io服務器在代理后面):

location /foo/ {
    proxy_pass http://foobar:3005/;
    proxy_http_version 1.1;                  # 新增
    proxy_set_header Upgrade $http_upgrade;  # 新增
    proxy_set_header Connection "upgrade";   # 新增
    proxy_set_header Host $host;             # 新增
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM