Jethro Hazelhurst
Jethro Hazelhurst

Reputation: 3285

Am I using websockets correctly?

Background:

How I am using it

I am building a slide-show that is controlled by a single user. If I want that one person to change the slide for all the people on that page then I make an AJAX call with the number slide that the user moved to.

$('#nextCard').click(function(){
    if ($('#card-' + (cardId + 1)).length != 0) {  // if there is a next card
        $('#card-' + (cardId)).hide();             // hide current card
        cardId++;                                  // increment the card id
        $('#card-' + (cardId)).show();             // and show the next card
        location.hash = cardId;

        /**
         * make ajax call to push function
         */
        $.ajax({
            method: 'post',
            url: '<?php echo base_url('learn/pusher'); ?>',
            data: {card_id: cardId},
            dataType: 'json',
            async: false,
        });
    }
});

This number is sent via ajax to the server where it is channelled via pusher.

Pusher then sends the slide number real time to all users on the same page... in effect pushing changes to different peoples screens.

var channel = pusher.subscribe('notifications');
channel.bind('new-notification', function(data) {

    // call something here

});

Then the changes are effected by the function that is called when the data is pushed.

My question

I was under the impression that Websockets was an alternative/replacement to AJAX and other similar technologies...but here I find myself relying on AJAX to send my Websockets data to pusher from the server side.

I thought that Websockets was advantageous over AJAX because it was faster, but here I find myself being bottlenecked by AJAX.

So am I using websockets correctly here?

Upvotes: 0

Views: 520

Answers (1)

Will Sewell
Will Sewell

Reputation: 2643

Using AJAX to send requests to your server which in turn triggers a Pusher event in order to broadcast it to subscribers is an idiomatic way of using Pusher. The underlying WebSockets technology is bidirectional (more info here), but Pusher's pub/sub model is unidirectional.

One alternative for your use-case is to use client events. This allows you to trigger events directly from the client. The extra consideration with doing this is you have to use private or presence channels.

Upvotes: 2

Related Questions