We’ll also need to add links to jQuery and a JavaScript file that will contain
our code to communicate with our web-sockets server. These can go right
above the closing <body> tag.
html5_websockets/index.html
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<scriptsrc='javascripts/chat.js'></script>
Our style sheet, which we create in stylesheets/style.css, contains these style
definitions:
html5_websockets/stylesheets/style.css
Line 1 #chat_wrapper{
- background-color:#ddd;
- height:440px;
- padding:10px;
5 width:320px; - }
- #chat_wrapperh2{ margin:0; }
10 #chat{
- background-color:#fff;
- height:300px;
- overflow:auto;
- padding:10px;
(^15) width:300px;
- }
On line 13, we set the overflow property on the chat message area so that its height
is fixed and any text that doesn’t fit should be hidden, viewable with scroll bars.
With our interface in place, we can get to work on the JavaScript that will
make the interface talk with our chat server.
Talking to the Server
No matter what web-sockets server we’re working with, we’ll use the same
pattern over and over. We’ll make a connection to the server, and then we’ll
listen for these events from the server and respond appropriately:
Event Description
onopen() Fires when the connection with the server has been established
onmessage() Fires when the connection with the server sends a message
onclose() Fires when the connection with the server has been lost or closed
report erratum • discuss
Chatting with Web Sockets • 221
Download from Wow! eBook <www.wowebook.com>