Djangowebosketredis不发布消息

2024-10-02 22:26:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我是django websocketredis的新手,不能用它发布消息。接收心跳消息,但关于从后端发布的消息,前端只接收最后一条消息(页面重新加载后),其他消息被忽略。下面是我的代码结构:

-mysite 
   |- __init__.py
   |-settings.py
   |-urls.py
   |-wsgi.py
-websockets
   |-migrations
       |-__init__.py
   |-templates
       |-index.html
   |-__init__.py
   |-admin.py
   |-models.py
   |-tests.py
   |-urls.py
   |-views.py
-db.sqlite3
-manage.py

以及设置.py公司名称:

^{pr2}$

网络插座/视图.py公司名称:

class BroadcastChatView(TemplateView):
template_name = 'websockets/index.html'

def get(self, request, *args, **kwargs):
    welcome = RedisMessage('Hello everybody')  # create a welcome message to be sent to everybody
    RedisPublisher(facility='foobar', broadcast=True).publish_message(welcome)
    return super(BroadcastChatView, self).get(request, *args, **kwargs)

网络插座/索引.html公司名称:

<div id="billboard"></div>
<button type="button" id="send_message">click to send message</button>
<!--<input type="text" id="text_message">-->

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script src="{{ STATIC_URL }}js/ws4redis.js" type="text/javascript"></script>
<script>
    jQuery(document).ready(function($) {
    var ws4redis = WS4Redis({
        uri: ' ws://localhost:8080/ws/foobar?subscribe-broadcast&publish-broadcast&echo',
        receive_message: receiveMessage,
        heartbeat_msg: {{ WS4REDIS_HEARTBEAT }}

    });
    var billboard = $('#billboard');

    // attach this function to an event handler on your site
    function sendMessage() {
        ws4redis.send_message('A message');
    }

    // receive a message though the websocket from the server
    function receiveMessage(msg) {
        console.log('Message from Websocket: ' + msg);
        billboard.append('<br/>' + msg);
        billboard.scrollTop(billboard.scrollTop() + 25);
    }

    $('#send_message').click(function() {
        ws4redis.send_message("hello");
    });

});
</script>

还有我的网站/wsgi.py公司名称:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
from django.conf import settings
from django.core.wsgi import get_wsgi_application
from ws4redis.uwsgi_runserver import uWSGIWebsocketServer

_django_app = get_wsgi_application()
_websocket_app = uWSGIWebsocketServer()


def application(environ, start_response):
    if environ.get('PATH_INFO').startswith(settings.WEBSOCKET_URL):
        return _websocket_app(environ, start_response)
    return _django_app(environ, start_response)

Tags: djangofrompysend消息wsgimessageget