Chatting with Web Sockets

About Chatting with Web Sockets

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 for Chatting with Web Sockets

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. We can use W e b Sockets to build all kinds of great applications. One of the best ways to get a feel for how W e b 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 W e b 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. W e won’t be writing the actual server for this, because that has thankfully already been written by another developer to Chatting with Web Sockets.

The Chat Interface for Chatting with Web Sockets

We are looking to build a very simple chat interface on the next 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 to Chatting with Web Sockets.

Chatting with Web Sockets

Chatting with Web Sockets

<div id="chat_wrapper">
<h2>AwesomeCo Help!</h2>
<form id="nick_form" action="#" method="post" accept-charset="utf-8">
<p>
<label>Nickname
<input id="nickname" type="text" value="GuestUser"/>
</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>
</div>

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 for Chatting with Web Sockets.

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

Our style sheet contains these style definitions:

chat_wrapper{
width: 320px;
height: 440px;
background-color: #ddd;
padding: 10px;
}
#chat_wrapper h2{
margin: 0;
}

#chat{
width: 300px;
height: 300px;
overflow: auto;
background-color: #fff;
padding: 10px;
}

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 to Chatting with Web Sockets.

Event         Description
onopen()     Fires when the connection with the server has been
              established
on message()  Fires when the connection with the server sends a
              message  
onclose()    Fires when the connection with the server has been
              lost or closed

In our chat.js file, we first need to connect to our Web Sockets server, like this for Chatting with Web Sockets:

var webSocket = new WebSocket('ws://localhost:9394/');

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 = function(event){
$('#chat').append("<br>" + event.data);
$('#chat').animate({scrollTop: $('#chat').height()});
};

The message comes back to us via the event object’s data property for Chatting with Web Sockets. We just add it to our chat window. W e ’ l 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.

webSocket.onclose = function(event){
$("#chat" ).append('<br>Connection closed');
};

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

$(function(){
$("form#chat_form" ).submit(function(e){
e.preventDefault();
var textfield = $( "#message" );
webSocket.send(textfield.val());
textfield.val("" );
});
}

We hook into the form submit event for Chatting with Web Sockets, 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" ).submit(function(e){
e.preventDefault();
var textfield = $( "#nickname" );
webSocket.send("/nick " + textfield.val());
});

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 with Chatting with Web Sockets

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, implementing a Flash fallback is a piece of cake. We can download a copy of the plug-in 10 and place it within our project. We then need to include the three JavaScript files on our page to Chatting with Web Sockets:

<script type="text/javascript" src="websocket_js/swfobject.js"></script>
<script type="text/javascript" src="websocket_js/FABridge.js"></script>
<script type="text/javascript" src="websocket_js/web_socket.js"></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>Nickname
<input id="nickname" type="text" value="GuestUser"/>
</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>
</div>
</body>
</html>

With that inp lace, our chat application will worko n allm ajor browsers, provided that the server hosting your chat server also serves a Flash Socket Policy file. Flash Socket Policyi 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 to Chatting with Web Sockets. 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  The example code for this section contains a simple Flash Socket Policy server written in Ruby that you can use for testing.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.

Chatting with Web Sockets

The book’s source code distribution contains a version of the Web Sockets for Chatting with 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 server.rb

In addition to the chat server, there are two other servers you may want to use while testing the examples in this chapter for server, client.rb, serves the chat interface . 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 to Chatting with Web Sockets.

andcombd