Array

Web Sockets

Must Read

Inside the Maguire Correctional Facility – San Mateo County’s Jail

Have you ever wondered how an inmate is booked into a jail? As bail bondsmen, clients and others often...

Powerhouse Online Business Systems – every imaginable niche blog

If you choose a system for online marketing on the Internet's most effective and dynamic use of blogs. Blogs...

Internet Marketing Guide – What you need, go to Beyond the Basics

Almost every Internet marketing guide you'll find online works best for beginning marketers. There are a few exceptions but...

Personal Injuries From Premises Neglect Can Get Complicated

The law states that each person has a liability to maintain his own premises in such a way that...

Discover How Home Equity Loans For People With Bad Credit Could Help You

As we all continue to deal with the consequences of the global credit crunch, it could appear strange to...

How to Avoid a Second DUI Charge

Getting a DUI charge can feel like swimming deep into the ocean; you know you made a mistake, but...
Admin
test

Real-time interaction has been something web developers have been trying to do for many years, but most of the implementations have involved using JavaScript to periodically hit the remote server to check for changes. HTTP is a stateless protocol, so a web browser makes a connection to a server, gets a response, and disconnects. Doing any kind of real-time work over a stateless protocol can be quite rough. The HTML5 specification introduced Web Sockets, which let the browser make a stateful connection to a remote server.7 We can use Web Sockets to build all kinds of great applications. One of the best ways to get a feel for how Web Sockets work is to write a chat client, which, coincidentally, AwesomeCo wants for its support site.

AwesomeCo wants to create a simple web-based chat interface on its support site that will let members of the support staff communicate internally, because the support staff is located in different cities. We’ll use Web Sockets to implement the web interface for the chat server.
Users can connect and send a message to the server. Every connected user will see the message. Our visitors can assign themselves a nickname by sending a message such as “/nick brian,” mimicking the IRC chat protocol. We won’t be writing the actual server for this, because that has thankfully already been written by another developer.

The Chat Interface

We’re looking to build a very simple chat interface that looks like Figure 10.2, on the next page, with a form to change the user’s nickname, a large area where the messages will appear, and, finally, a form to post a message to the chat.

In a new HTML5 page, we’ll add the markup for the chat interface, which consists of two forms and a div that will contain the chat messages.

<div id=”chat_wrapper”>
<h2>AwesomeCo Help!</h2>
<form id=”nick_form” action=”#” method=”post” accept-charset=”utf-8″>
<p>
<label>Ni ckname
<input id=”nickname” type=”text” value=”Guestl)ser”/>
</label>
<input type=”submit” value=”Change”>
</p>
</form>
<div id=”chat”>connecting….</div>
<form id=”chat_form” action=”#” method=”post” accept-charset=”utf-8″>
<p>
<label>Message
<input id=”message” type=”text” />
</label>
<input type=”submit” value=”Send”>
</p>
</form>
< / d i v >

We’ll also need to add links to a style sheet and a JavaScript file that will contain our code to communicate with our Web Sockets server.

<script src=’chat.js’ type=’text/javascript’></script>
<link rel=”stylesheet” href=”style.css” media=”screen”>

Our style sheet contains these style definitions:

Une l #chat_wrapper{
w i d t h : 320px;
h e i g h t : 440px;
b a c k g r o u n d – c o l o r : #ddd;
5 padding: lOpx;
}
#chat_wrapper h2{
m a r g i n : 0;
}
# c h a t {
w i d t h : 300px;
h e i g h t : 300px;
o v e r f l o w : auto;
15 background-color: #fff;
p a d d i n g : lOpx;
}

On line 14, 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 scrollbars.

With our interface in place, we can get to work on the JavaScript that will make it 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 events from the server and respond appropriately.

EventIn our chat.js file, we first need to connect to our Web Sockets server, like this:

v a r webSocket = new W e b S o c k e t ( ‘ w s : / / l o c a l h o s t : 9 3 9 4 / ‘ ) ;

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

webSocket.onopen = f u n c t i o n ( e v e n t ) {
$ ( ‘ # c h a t ‘ ) . a p p e n d ( ‘ < b r > C o n n e c t e d to the s e r v e r ‘ ) ;
};

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:

webSocket.onmessage = f u n c t i o n ( e v e n t ) {
$ ( ‘ # c h a t ‘ ) . a p p e n d ( ” < b r > ” + e v e n t . d a t a ) ;
$ ( ‘ # c h a t ‘ ) . a n i m a t e ( { s c r o l l T o p : $ ( ‘ # c h a t ‘ ) . h e i g h t O } ) ;

The message 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 wanted.

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

w e b S o c k e t . o n c l o s e = f u n c t i o n ( e v e n t ) {
$ ( ” # c h a t ” ) . a p p e n d ( ‘ < b r > C o n n e c t i o n c l o s e d ‘ ) ;
};
};

Now we just need to hook up the text area for the chat form so we can send our messages to the chat server.

$ ( f u n c t i o n ( ) {
$( “form#chat_form”) . submi t ( f u n c t i o n ( e ) {
e . p r e v e n t D e f a u l t ( ) ;
v a r t e x t f i e l d = $(“#message”) ;
w e b S o c k e t . s e n d ( t e x t f i e l d . v a l ( ) ) ;
t e x t f i e l d . v a l ( ” ” ) ;
} ) ;

We hook into the form submit event, 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.

$( “form#nick_form”) . submi t ( f u n c t i o n ( e ) {
e . p r e v e n t D e f a u l t ( ) ;
var t e x t f i e l d = $(“#m’c/cname”) ;
webSocket.send(“/m’c/c ” + t e x t f i e l d . v a l ( ) ) ;
} ) ;

That’s all there is to it. Safari 5 and Chrome 5 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-js9 library, implementing a Flash fallback is a piece of cake.

We can download a copy of the plug-in10 and place it within our project. We then need to include the three JavaScript files on our page:

<script type=”text/javascript” src=”websocket_js/swfobject.js”x/script>
<script type=”text/javascript” src=”websocket_js/FABridge.js”x/script>
<script type=”text/javascript” src=”websocket_js/web_socket.js”x/script>
<script src=’chat.js’ type=’text/javascript’></script>
<link rel=”stylesheet” href=”style.css” media=”screen”>
</head>
<body>
<div id=”chat_wrapper”>
<h2>AwesomeCo Help!</h2>
<form id=”nick_form” action=”#” method=”post” accept-charset=”utf-8″>
<p>
<label>Ni ckname
<input id=”nickname” type=”text” value=”Guestl)ser”/>
</label>

<input type=”submit” value=”Change”>
</p>
</form>
<div id=”chat”>connecting….</div>
<form id=”chat_form” action=”#” method=”post” accept-charset=”utf-8″>
<p>
<label>Message
<input id=”message” type=”text” />
</label>
<input type=”submit” value=”Send”>
</p>
</form>
< / d i v >
</body>
</html>

The only change we need to make to our chat.js file Is to set a variable that specifies the location of the WebSocketMain file.

WEB_SOCKET_SWF_|_OCATION “websocket_js/WebSocketMain. swf” ;

With that In place, our chat application will work on all major browsers, provided that the server hosting your chat server also serves a Flash Socket Policy file.

Flash Socket Policy What?

For security purposes, Flash Player will only communicate via sockets with servers that allow connections to Flash Player. Flash Player attempts to retrieve a Flash Socket Policy file first on port 843 and then on the same port your server uses. It will expect the server to return a
response like this:

<cross-domain-policy>
<allow-access-from domain=”*” to-ports=”*” />
</cross-domain-policy>

This Is a very generic policy file that allows everyone to connect to this service. You’d want to specify the policy to be more restrictive if you were working with more sensitive data. Just remember that you have to serve this file from the same server that’s serving your Web Sockets server, on either the same port or the port 843.

The example code for this section contains a simple Flash Socket Policy server written in Ruby that you can use for testing. See Section 25,

Servers, for more on how to set that up on your own environment for testing.

Chat servers are just the beginning. With Web Sockets, we now have a robust and simple way to push data to our visitors’ browsers.

Servers

The book’s source code distribution contains a version of the Web Sockets server we’re targeting. It’s written in Ruby, so you’ll need a Ruby interpreter. For instructions on getting Ruby working on your system, see the file RUBY_README.txt within the book’s source code files.

You can start it up by navigating to its containing folder and typing this:

ruby s e r v e r . r b

In addition to the chat server, there are two other servers you may want to use while testing the examples in this chapter. The first server, client.rb, serves the chat interface and JavaScript files. The other server, flashpolicyserver, serves a Flash Policy file that our Flash-based Web Sockets fallback code will need to contact in order to connect to the
actual chat server. Flash Player uses these policy files to determine whether it is allowed to talk to a remote domain.

If you’re running on a Mac or a Linux-based operating system, you can start all these servers at once with this:

rake s t a r t

from the html5_websockets folder.

 

 

Latest News

Digital Marketing for Beginners

Digital marketing for starter, Let to basic learning about connecting with your audience in the right place at the...

What are 7 things poor people do that the rich don’t?

1. poor people watch TV in which people read books how many hours you spend in front of the TV and when was the...

Top 18 best small business ideas for beginners starting

A small business can be frightening and requires plenty of careful planning there are many small business ideas which can be beneficial as well...

Summer that makes you happy

We saw were already here I've been thinking about some of the things. I used to do with my husband even though he had...

4 Point to helpful tips specifically for caregivers

What you need to take a vacation. I know it sounds impossible creative and try to make it work for you almost everyone needs...

More Articles Like This