2012/09/06

An Introduction on HTML5 WebSocket

WebSocket is the new function introduced in html5 and is used to solve the problems in the mutual communications between the browser and the back-end server. With the help of WebSocket technology, the back-end server will be able to send messages to the front-end at any time to ensure the unity of foreground and background, which is out of the question in the tradition stateless HTTP protocol.

The Traditional Server Push
Before the existence of WebSocket, in order to meet the requirement of sending messages to the fore-end from the back-end, some solutions of the existing technologies have been put forward (like ajax, iframe, flashplayer, java applet, etc.) or just make some changes to them to try to satisfy the requirement.

Simple Polling
This is the simplest way. The back-end is asked at intervals to obtain the latest state, which is the easiest to realize, but the effect is awful. It is wasteful and of bad instantaneity, for once there is a renewal in the back-end, the fore-end will know it only after the next polling.

Long Polling
To solve the problems above, long polling came into existence. Polling requests will bock in the back-end, which means that there will be a long connection and returns until a renewal or a time-out appears. In this way, the promptness of the renewals can be ensured. When the fore-end gets the request, it will reestablish the connection to await the notice of renewal from the background.

Other Solutions
Other solutions are about a long connection (like Iframe and htmlfile), which instantly gets information from the back-end or with the aid of the third plug-in (flashPlayer and jre). It uses flash xml socket or java applet socket technology; however, these solutions rely on plug-ins, namely, not pure-html enough. For more traditional server push technology please refer to the article of IBM:
http://www.ibm.com/developerworks/cn/web/wa-lo-comet/

An Introduction on WebSocket
WebSocket is the new technology introduced in html5. It allows the back-end to send texts or binary messages to the fore-end. WebSocket is a new protocol, not belonging to the stateless protocol of http. The protocol name is “ws”, which means that a websocket link address is like this: ws://twaver.com:8080/webSocketServer. “ws”is not http, so the traditional web server does not necessarily support it. Thus WebSocket can run normally only when both the server and the browser support it. But the currently the support is not common and the special web server and the modern browser are needed.

The Support of the Server to WebSocket
Google Chrome browser is the first to support WebSocket, then Safari and Firefox. In addition, Opera and IE of the latest edition (Opera11 and IE10) are also compatible with WebSocket.
The following is the support of the main browsers to WebSocket. Here Opera 11 is not listed, for it has closed the support as default. For more information: http://en.wikipedia.org/wiki/WebSocket and http://caniuse.com/#search=websockets
 


The Main Methods of WebSocket at Client-side
Different browsers have different level of support toward WebSocket. The chapter “Browser support” which is on WebSocket in wiki has introduced that the browser has provided WebSocket class (MozWebSocket class in Firefox), which conforms to the related rule of w3c on WebSocket API. To check whether the browser is compatible with WebSocket or not, you can use the following script code: 

To check whether the browser is compatible with WebSocket or not
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket){
    alert("WebSocket not supported by this browser");
    return;
}
Constructor function– WebSocket#constructor(url, optional protocols)
The first parameter is used to ask for the addres;  the second, parameteris optional (the protocol name).
Example:
var websocket = new WebSocket("ws://127.0.0.1:8080/alarm/alarmServer");
events – open/message/close/error    
WebSocket#onopen, onmessage, onclose, onerror
When the connection is open, after calling back the method onopen, the event onmessage will be triggered on receiving the messages from the back-end. The method onclose will be called when the back-end is closed. Any error that occur when connecting will be told if calling the method onerror.
Example:
websocket.onmessage = function(evt){
    var data = evt.data;
}
method – send/close
sending mesages WebSocket#send(data)
closing the connection – WebSocket#close(optional code, optional reason)
Example:
websocket.send(JSON.stringify({action: "node.remove", id: "001"}));
The support of the server to WebSocket
WebSocket is different from http protocol, for the traditional web servers generally don’t support WebSocket, such as the tomcat at the present (tomcat 7.0.26 has supported WebSocket now). Instead, some minority or more active web servers are among the first to support it like jetty and the Node expander of WebSocket which is based on node.js. Generally every programming language has the corresponding server to choose. I have here listed some of them in the following. For more detailed information please refer to:
http://en.wikipedia.org/wiki/Comparison_of_WebSocket_implementations



The programming languages for different servers are different, hence the difference in their concrete implementations. Even if the same language, the implementation class and the interface function are also distinct. For example, though jetty and netty are all based on java language, there is nearly no two implementation classes with the same name. Now taking jetty (http://www.eclipse.org/jetty) as an example, I will introduce the classes and methods related to WebSocket.



WebSocket in jetty
Based on servlet standard, the method doWebSocketConnect(…) has been added into WebSocketServlet to ask to create a corresponding WebSocket instance of the back-end for the client-side.
org.eclipse.jetty.websocket.WebSocketServlet
{
WebSocket doWebSocketConnect(HttpServletRequest request, String protocol)
}
The WebSocket class at the back-end is corresponding to that at the client side. It is able to listen to the state-changed events like “open”, “message” and “close”. What’s more, it also involves a “Connection” property, which is used to send messages to the client-side.
org.eclipse.jetty.websocket.WebSocket
org.eclipse.jetty.websocket.WebSocket.OnTextMessage
{
void onOpen(Connection connect);
void onClose(int code, String message);
void onMessage(String message);
}
WebSocket.Connection back-end-connection class which is involved in WebSocket object, is used to send messages to the client-side.
org.eclipse.jetty.websocket.WebSocket.Connection
{
void sendMessage(String message);
}
This article is just an introduction. Later on we will introduce an instance in which WebSocket and TWaver components are combined together.



No comments:

Post a Comment