Clash of Clicks

A game... kind of...

Websockets?

Basically, both the client and server can send a message whenever they want

Examples

  • Chat room
    • Message appears for everyone in the room
    • "user X is typing..."
  • Live Blog
  • Sports Tracker

Clash of Clicks Demo

https://clashofclicks.herokuapp.com

The HTML

<div>Clientside:
    <span id="clientside-counter">{{ counter }}</span>
</div>
<div>Websockets:
    <span id="websockets-counter">{{ counter }}</span>
</div>

The Click

$("#update").click(function() {
    socket.send(JSON.stringify({
        "increment": true,
    }));

    $('#clientside-counter').html(function(i, val) {
       return parseInt(val)+1;
    });
});

Django Counter

# models.py
class Counter(models.Model):
    user = models.OneToOneField(auth.User)
    count = models.IntegerField(default=0)


# consumers.py
def ws_receive(message):
    payload = json.loads(message['text'])
    if payload.get('increment', False):
        message.user.counter.count += 1
        message.user.counter.save()
    message.reply_channel.send(
        {'text': {'action': 'update_self',
                  'count': message.user.counter.count}})

Browser Update

socket.onmessage = function (message) {
    var data = JSON.parse(message.data);
    if (data.action == 'update_self') {
        $('#websockets-counter').html(data.count);
    }
}

Groups: The Special Sauce

# Creating a new connection
def ws_connect(message):
    Group('active').add(message.reply_channel)

# Receiving a new click notification
def ws_receive(message):
    payload = json.loads(message['text'])
    if payload.get('increment', False):
        message.user.counter.count += 1
        message.user.counter.save()
    Group('active').send(
        {"text": {'action': 'update',
                  'user': message.user.username,
                  'count': message.user.counter.count}})

Implementing the "Active Users" list

Overhead Test

  • Every click results in a message to each active user
  • How fast can you click?

The Code

https://github.com/m3brown/click-clash/

Clash of Clicks

By m3brown

Clash of Clicks

  • 1,358