HTML5 and CSS3, Second Edition

(singke) #1
Now we just need to hook up the text area for the chat form so we can send
our messages to the chat server. This handler also goes in the setupChat()
function:

html5_websockets/javascripts/chat.js
$("form#chat_form").submit(function(e){
e.preventDefault();
vartextfield= $("#message");
webSocket.send(textfield.val());
textfield.val("");
});

We hook into the form submission, grab the value of the form field, and send
it to the chat server using the send() method.

We implement the nickname-changing feature the same way, except we prefix
the message we’re sending with “/nick. ” The chat server will see that and
change the user’s name.

html5_websockets/javascripts/chat.js
$("form#nick_form").submit(function(e){
e.preventDefault();
vartextfield= $("#nickname");
webSocket.send("/nick"+ textfield.val());
});

Finally, we can call the setupChat() function, so all of these events get called.


html5_websockets/javascripts/chat.js
setupChat();

In a more complex app, it’d be much better to break the setupChat() method
into individual methods that each do their own thing. But this works and
proves the concept we’re exploring.

That’s all there is to it. Safari, Firefox, and Chrome users can immediately
participate in real-time chats using this client. Of course, we still need to
support browsers without native Web Sockets support. We’ll do that using
Flash.

Falling Back


Browsers may not all have support for making socket connections, but Adobe
Flash has had it for quite some time. We can use Flash to act as our socket
communication layer, and thanks to the web-socket-js library,^7 implementing
a Flash fallback is a piece of cake.


  1. http://github.com/gimite/web-socket-js/


report erratum • discuss

Chatting with Web Sockets • 223


Download from Wow! eBook <www.wowebook.com>

Free download pdf