Placed in: Home viagra australia
viagra online
viagra sale
cialis online
cialis australia
Working with Websockets

HTML5 has some extremely cool features, and a couple of weeks ago I took a deep dive into Websockets. This protocol, which you can recognize by the ws:// and wss:// (secure websockets) URL prefix, enables "Server side push events".

Working with Websockets

During my deep dive, I learned a couple of things that are pretty interesting. If you're into/learning HTML5, you really should try out Websockets! In my opinion, it's one of the coolest technologies they've added. Are you ready to dive and learn more about Websockets? Here are a couple of things to keep in mind when working with Websockets.

What are Websockets?

Websockets Icon

Websockets enable Web applications to maintain bidirectional communications with server-side processes (as stated by API). In other words: It enables the server to push data to the connected clients. Examples of application in which this would be useful:

  • Chat application.
  • Multi-player game (like Quake 2).
  • An application where live data is needed, like a stock market app.

Previously, the most common method to achieve this is used by polling or using comet. The client would ask the server if there is any (new) data that he could use and if there was, it would react to it. There are a couple of downsides of this method, and two important ones are:

  • Heavy traffic / loads of server requests.
  • Messages are not delivered "instantly"; They always have some kind of delay.

If you need to write a web application that needs to support this kind of stuff, Websockets is your choice.

Your browser

Browsers

First things first: The browser where the application will be running in, will need to support the Websocket protocol. As you can see in the related specifications of the current HTML5 layout engines, only Webkit browsers support it properly (Chrome, Safari and even Mobile Safari). Status for the other browser layout engines: Gecko (Firefox) is Experimental, Trident (Internet Explorer) is Partial and for Presto (Opera), it Depends.

For the sake of this article, we assume your browser fully supports the websockets protocol. Using Modernizr, you can easily check if the browser that is viewing the application supports Websockets (Below, you'll find the implementation without Modernizr).

Your server

Server

The protocol is created in such a way, that your webserver also needs to support it. The server needs the following:

  • Be online
  • Support ws:// or wss://
  • Listen actively to a specified port for incoming websocket connections
  • Support the correct handshake that the client also supports

That's what you need for your server to "understand" and support the Websocket protocol.

Client side code

If you know all about the browser and what the server needs, programming with Websockets is actually pretty easy! First, let's define the websocket URL (the location of the server):

 
var WEBSOCKET_URL = "ws://[YourHost]:[YourPort]/";

Ofcourse, you'll need to change [YourHost] to the location of your host, and [YourPort] to the port the server is listening to for Websocket communication. Now, we'll check if the browser supports the Websocket protocol.

 
var support = "MozWebSocket" in window ? 'MozWebSocket' : ("WebSocket" in window ? 'WebSocket' : null);
if (support == null) {
    alert("Your browser doesn't support Websockets.");
    return;   
}

Since the Websocket implementation from Gecko (Firefox) is still Experimental, that browser needs the Moz prefix. We than check if any of both values is available in the browser; If not, alert the user. The next step is to create the actual Websocket connection:

 
var ws = new window[support](WEBSOCKET_URL);

At this point, the browser tries to open up a websocketconnection with the given Websocket URL. The following two methods will become interesting to know if the connection has been established.

 
// Called when the connection to the server is opened.
ws.onopen = function () {
    alert("Connection with server open.");
};
 
// Called when the connection to the server is closed.
ws.onclose = function () {
    alert("Connection with server closed; Maybe the server wasn't found, it shut down or you're behind a firewall/proxy.");
};

If we assume the connection to the server has succesfully been opened, two other methods will give us the full power of Websockets. The first one is onmessage, the second send:

 
// When the server is sending data to this socket, this method is called
ws.onmessage = function (evt) {
    
    // Received data is a string; We parse it to a JSON object using jQuery
    // http://api.jquery.com/jQuery.parseJSON/
    var jsonObject = $.parseJSON(evt.data);
    
    // Do something with the JSON object
};
 
 
// Creates an object that will be sent to the server
var myObject = {
    Property: "Value",
    AnotherProperty: "AnotherValue"
};
 
// We need to stringify it through JSON before sending it to the server
ws.send(JSON.stringify(myJsonObject));

Since we can't send the JSON object as true JSON object to the server, we need to stringify (serialize) it before we can send it. The same counts for receiving the message: It's a (well-formed) string, that we need to convert to a JSON object. In this case, I've used the $.parseJSON from jQuery to convert the string to the object.

That's all there is to it for your client! Just a simple check if the client supports Websockets, and if it does, handle the onopen, onclose, onmessage events and call the call method. Now let's dive into the server side code to see how it can work there.

Server side code

Now this is going to be interesting; There are several implementations available for a Websocket server. Just make sure you pick one that supports the correct protocol/handshake in order to make it fully work. There are Java implementations, but since I prefer .NET, SuperWebSocket has been helping me out a lot. Simply use Google to search for a Websocket server implementation for the platform of your choice.

Take note, this following C# code example is not complete; I just trimmed it down to the bone to show you what kind of stuff you need on the server to support Websockets.

 
// List which contains the information about the several socket connections
private List<WebSocketSession> _sessions = new List<WebSocketSession>();
 
// Method to create the WebsocketServer
private void StartWebsocketServer() {
    var socketServer = SocketServerManager.GetServerByName("SuperWebSocket") as WebSocketServer;
    socketServer.NewMessageReceived += OnNewMessageReceived;
    socketServer.NewSessionConnected += OnNewSessionConnected;
    socketServer.SessionClosed += OnSessionClosed;
}
 
// Event which is called when a new client is connected
void OnNewSessionConnected(WebSocketSession session) {
    _sessions.Add(session);
}
 
// Event which is called when a client disconnects
void OnSessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason e) {
    _sessions.Remove(session);
}
 
// Event which is called when a message from the client is received
void OnNewMessageReceived(WebSocketSession session, string e) {
    var cSharpObject = JsonConvert.DeserializeObject<CSharpObject>(e);
    foreach (var s in _sessions) {
        s.SendResponseAsync(JsonConvert.SerializeObject(cSharpObject));
    }
}

I hope this code is pretty straightforward; Three simple methods which handle the server side events that can handle the client side calls. I've used a library from Newton-King to (de)serialize to/from the C# object and the JSON object. When it's a C# object, you can do all kinds of stuff (for example: store it to the database).

That's about it! When a message is received from a client, the server receives it and sends the message back to all the connected clients. Can you imagine what you can do with more client and server side logic!

Conclusion

Sadly, as you can see, there a loads of hooks when you want to work with Websockets. They are pretty awesome, but your browser and the server need to support it. There isn't a very proper fallback mechanism, mainbly because of the delay when working with applications that require instant updates.

What are your thoughts? Did you already work with Websockets before? If not, why? And if you did, where/how did you use it? Feel free to share!


Tags:  html5 websockets connectivity tips

Interested in this topic? You might enjoy another article I've written called

Did you like this article? Subscribe to my feed or email to keep updated on new articles.

Spread the word and submit to:
Digg!Reddit!Del.icio.us!Facebook!StumbleUpon!
 
< Prev   Next >
Subscribe

Subscribe to Marcofolio