Frage

I'm trying to use django-websocket-redis and I didn't understand how it works even reading the doc.. The part client (javascript/template) was easy to understand but I want to send data messages from one client to other and i'm blocking here..

Connecting each client :

var ws = new WebSocket('ws://localhost:8000/ws/foobar?subscribe-group');
ws.onopen = function(e) {
        console.log("websocket connected");
    };
    ws.onclose = function(e) {
        console.log("connection closed");
    };

How manage my views.py to create a link between them ? With NodeJS I was using this code to link the clients together :

io.sockets.on('connection', function (socket) {
    var data={"action": "connexion", "session_id": socket.id,};
    socket.emit('message',data);

    socket.on('message', function(socket){
        if (socket.action == "test")
        {
            io.sockets.socket(socket.code).emit('message',{"action": "move"}); 
            //the socket.code is the session_id of the client one transmitted by a form
        }
    });
});

Thanks you.

War es hilfreich?

Lösung

The link between your Django view.py and the Websocket loop is the Redis message queue. Imagine to have two separate main loops on the server: One which handles HTTP-requests using the normal Django request handler. The other loop handles the Websockets, with their long living connections. Since you can't mix both loops within the normal Django request handler, you need message queuing, so that they can communicate to each other.

Therefore, in your Django view.py, send the data to the websocket using something like:

def __init__(self):
    self.redis_publisher = RedisPublisher(facility='foo', broadcast=True)

def get(self, request):
    data_for_websocket = json.dumps({'some': 'data'})
    self.redis_publisher.publish_message(RedisMessage(data_for_websocket))

This will publish data_for_websocket on all Websockets subscribed (=listening) using the URL:

ws://example.com/ws/foo?subscribe-broadcast
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top