Navigation

A Step-by-Step Tutorial of Building a Simple Peer-to-Peer WebSocket App – Part 7

August 17, 2012

In Part 1, we looked at the completed application, then reviewed the starting code in Part 2. In Part 3 we created a WebSocket connection and started sending and receiving messages in Part 4. In Part 5 we solved the problem of hearing back the echo of the same messages we were sending to the other clients. In Part 6, we added an image that resizes in all participating browsers the slider is moved.

In this part we address the problem of accumulating messages and potentially degraded performance when the slider is moved too fast.

Task 16: Defining supporting variables

In this task, we will set up a few variables that we’ll need later in this tutorial: the variable, called sending holds the state whether there are messages yet to be sent. The variable, called sliderQueue holds the accumulating messages that are yet to be sent.

var sending = false;
var sliderQueue = [];

Here’s the entire JavaScript file. Look for Task 16 in the comments to find the newly added function.

Task 17: Dealing with accumulating messages

In case the network cannot keep up with the message rate, you can follow a number of different strategies. Given the nature of our application, we’ll implement a solution in which we throw away all the accumulated slider states, except for the very last one, that we send over. If you move your slider constantly, and your network latency is sufficiently big, you will be able to observe that the image resize actions in the remote browser are somewhat granular or choppy.

In this task we write a function, called sendFromQueue that performs the following logic: If we have messages in the sliderQueue array, then we send the last message from the queue and clear the queue. Otherwise (if there are no messages in the sliderQueue), we switch to “not sending” state.

Task 18: Adding sendFromQueue() as the callback function of doSend()

Earlier on we wrote a doSend() function that is responsible for sending the messages every time the slider is moved. Back then we left the callback empty. Now that we wrote the sendFromQueue() function, let’s add it in there. This will ensure that when done with sending a message, sendFromQueue() is invoked, allowing us to send the last element from the queue and clear the rest of the messages from it.
We’re adding a single line of code to the doSend() function: sendFromQueue().

Task 19: Incorporating sliderQueue into the message sending logic

In this final task, let’s integrate the sliderQueue with our message sending logic. With this logic, when the slider changes, we’re either in the middle of sending a message or idle. If the app is busy sending a message, the message should be appended to the sliderQueue. If the app is not sending a message, then we should switch to sending mode, and send the message.