HTML5 and CSS3, Second Edition

(singke) #1
In our javascripts/chat.js file, we first need to connect to our web-sockets server,
like this:

html5_websockets/javascripts/chat.js
varsetupChat=function(){
// changethisto the IP addressof the websocketserver
varwebSocket=newWebSocket('ws://192.168.1.2:9394/');
};

We’re placing all of these event handlers inside a function called setupChat().
This will keep it a little more organized and let us control when we attach the
events, instead of having them run immediately. We’ll eventually need to
detect for socket support in the browser and load a fallback, so we don’t want
these events firing until we’re ready.

When we connect to the server, we should let the user know. We define the
onopen() method like this, inside the setupChat() function:

html5_websockets/javascripts/chat.js
webSocket.onopen=function(event){
$('#chat').append('<br>Connected to the server');
};

When the browser opens the connection to the server, we put a message in
the chat window. Next, we need to display the messages sent to the chat
server. We do that by defining the onmessage() method like this, again inside
of the setupChat() function:

html5_websockets/javascripts/chat.js
Line 1 webSocket.onmessage=function(event){
2 $('#chat').append("<br>"+ event.data);
3 $('#chat').animate({scrollTop:$('#chat').height()});
4 };

The message from the server comes back to us via the event object’s data
property. We just add it to our chat window. We’ll prepend a break so each
response falls on its own line, but you could mark this up any way you want.
On line 3, we use jQuery to make the chat window scroll so we can see the
new message at the bottom.

Next we’ll handle disconnections. The onclose() method fires whenever the
connection is closed.

html5_websockets/javascripts/chat.js
webSocket.onclose=function(event){
$("#chat").append('<br>Connectionclosed');
};

Chapter 10. Creating Interactive Web Applications • 222


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf