Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

422 CHAPTER 10 WebSocket communications


function onClose(evt) {
cancelKeepAlive();
writeOutput("DISCONNECTED");
}

function onMessage(evt) {
writeOutput('RESPONSE: ' + evt.data);
}

function onError(evt) {
writeOutput('ERROR: ' + evt.data);
}
In this example, the bold code was added. At the top is the declaration of the timerId.
A keepAlive function has been added that sends an empty message every 15 seconds. The
keepAlive function is called when the onOpen function is executed and is recursive; it doesn’t
stop until the timer is cancelled by using the timerId. A cancelKeepAlive function has been
added to cancel the looping of the keepAlive function, and it’s called when the onClose func-
tion is called.

Handling connection disconnects


In addition to providing the keepAlive capability, you might also need to deal with connec-
tions that close due to network errors. This can require you to call the connect function from
within the onClose function. Depending on your application, this could cause problems at
the server when the server doesn’t recognize that the new connection belongs to an existing
client. Your application might need to handle this by forcing the client to send an identifica-
tion message. Keep in mind that the messages are in the format that you dictate, so you can
define your own messaging strategy for your application.

Dealing with web farms


Sometimes, when pushing your WebSocket application to production, you need your applica-
tion to run in a web farm, when multiple servers handle incoming requests. These requests
are typically load balanced to provide the best performance. How can you have an open con-
nection to a server and still have load balancing?
When there are multiple web servers, you can implement sticky servers, by which the client
continuously goes to the same server it originally went to. This takes care of the open connec-
tion problem. You can share state across multiple web servers by using one of the many prod-
ucts that handle this problem, such as Redis (remote dictionary service) and the Microsoft
App Fabric Caching Service.
Just remember to test your web farm environment early for compatibility and problems
because you will surely need to adjust for this environment.

Key
Te rms
Free download pdf